Hacktoberfest 2026:维护者为十月标记出来的 issue,仍然开放、适合新手。 浏览 Hacktoberfest issue

Bad performance using useState

未关闭
#700 0 条评论 13 个 reaction 已指派 0 人 在 GitHub 查看

还没有人认领这个 Issue。

评估

难度
2/5
预计耗时
1-3 小时
新手友好度
45/100
Issue 类型
文档
描述清晰度
基本清楚
活跃度
停滞
技术栈
javascript, react
领域
documentation

调研方向

从 issue 中引用的第一个文档示例开始,检查其 onChange 回调如何使用 setValue。更新示例或随附的指导,解释重新渲染的成本以及何时适合使用 ref;当文档中的建议能够清楚地区分保存编辑器更改与有意更新 CodeMirror 值时,即视为完成。

由索引模型根据 Issue 内容生成。

描述

I think the first example in the documentation has a flaw.
It uses setValue(val) in the onChange callback which means that React triggers re-rendering of the component. In my case, when using a computationally heavy SQL editor this gets slowed down so much that it even misses characters when typing.

  const [value, setValue] = React.useState("console.log('hello world!');");
  const onChange = React.useCallback((val, viewUpdate) => {
    console.log('val:', val);
    setValue(val);
  }, []);
  return <CodeMirror value={value} height="200px" extensions={[javascript({ jsx: true })]} onChange={onChange} />;

Here is the IMO correct way to do it:

  const valueRef = React.useRef("console.log('hello world!');");
  const [value, setValue] = React.useState(valueRef.current);
  const onChange = React.useCallback((val, viewUpdate) => {
    console.log('val:', val);
    valueRef.current = val; // Update ref instead of state to avoid unnessecary re-renders
  }, []);
  return <CodeMirror value={value} height="200px" extensions={[javascript({ jsx: true })]} onChange={onChange} />;

So basically use setValue(val) only when you really want to change the code in your codemirror instance and thus want React to re-render your component. If you just want to store the internal state of your codemirror instance on changes for further use in your React component you should just use refs and access the actual value via valueRef.current.

主要语言
TypeScript
星标
2.3k
派生
162
平均合并
2 小时 41 分钟
30 天内合并 PR
1

环境准备

这个项目没有提供开发容器、Dockerfile 或贡献指南,环境需要你自己搭建:先看它的 README,通用步骤见我们的新手贡献指南。

从这里开始

  1. 先读完整个 Issue,再读项目的贡献指南。
  2. 在 Issue 下留言说明你要接手 —— 这能避免两个人做同样的事。
  3. Fork 仓库,在一个分支上完成修改。
  4. 提交 Pull Request,并在描述里引用这个 Issue 编号。

uiwjs/react-codemirror 的其他 Issue

查看 uiwjs/react-codemirror 的全部 Issue

相似的 Issue

更多 TypeScript Issue

把新 issue 发到你的邮箱

精选适合新手参与的 GitHub issue 摘要。