DEV Community

Sireesh
Sireesh

Posted on

React setState which way is right

This is very fundamental but need deep analysis, wic one is better approach.

In this code we are setting setState in onCheckChange, without useCallback.

const App = () => {
  const [checked, setChecked] = useState(false)

  // Without UseCallback
  const onCheckChange = () => {
    setChecked(!checked);
  };
  return (
    <div className="App">
      <input type="checkbox" onChange={onCheckChange} checked={checked} />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

In this code state will be updated through useCallback to avoid re-creation of onCheckChange

const App = () => {
  const [checked, setChecked] = useState(false)

  // Callback to update Sate
  const onCheckChange = useCallback(() => {
    setChecked(checked => !checked);
  }, [setChecked]);

  return (
    <div className="App">
      <input type="checkbox" onChange={onCheckChange} checked={checked} />
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)