Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Bad performance using useState #700

Open
luckfamousa opened this issue Nov 19, 2024 · 0 comments
Open

Bad performance using useState #700

luckfamousa opened this issue Nov 19, 2024 · 0 comments

Comments

@luckfamousa
Copy link

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant