uiwjs / uiwjs/react-codemirror

Bad performance using useState

Open
#700 0 comments 13 reactions 0 assignees View on GitHub

Nobody has claimed this yet.

Dominant language
TypeScript
Stars
2.3k
Forks
161
PR merge metrics
No merged PRs in 30d

Description

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.

Contributor guide

No contributing guide indexed for this repository

First steps

  1. Read the whole issue, then the project's contributing guide.
  2. Comment on the issue to say you are picking it up — it saves two people doing the same work.
  3. Fork the repository and make your change on a branch.
  4. Open a pull request that references the issue number.

Research direction

Start from the first documentation example referenced in the issue and review how its onChange callback uses setValue. Update the example or accompanying guidance to explain the re-rendering cost and when a ref is appropriate; done when the documented recommendation clearly distinguishes storing editor changes from intentionally updating the CodeMirror value.

Written by the indexing model from the issue text.

Assessment

Tech stack
javascript, react
Domain
documentation
Issue type
Documentation
Difficulty
2/5
Estimated time
1-3 hours
Activity status
Stale
Clarity
Mostly clear
Newbie friendliness
45/100

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.