Home > Blockchain >  React setState in function or setState in useCallback
React setState in function or setState in useCallback

Time:11-06

This looks simple but I am trying to find the best way of handling the state change, I know useCallback needed for large application but created the simple example for better understanding and deep analysis.

So I want to understand which one is better approach with useCallback or without useCallback for less re-render and create function only once.

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>
  );
}

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>
  );
}

CodePudding user response:

One could simply write since the identity of the function setChecked never changes.

const onCheckChange = useCallback(() => {
  setChecked(checked => !checked);
}, []);

Note

React guarantees that setChecked function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.

  • Related