React – Is useState ‘s setter function able to change?

The setter function won’t change during component life.

From Hooks FAQ:

(The identity of the setCount function is guaranteed to be stable so it’s safe to omit.)

The setter function (setState) returned from useState changes on component re-mount, but either way, the callback will get a new instance.

It’s a good practice to add state setter in the dependency array ([setState]) when using custom-hooks. For example, useDispatch of react-redux gets new instance on every render, you may get undesired behavior without:

// Custom hook
import { useDispatch } from "react-redux";

export const CounterComponent = ({ value }) => {
  // Always new instance
  const dispatch = useDispatch();

  // Should be in a callback
  const incrementCounter = useCallback(
    () => dispatch({ type: "increment-counter" }),
    [dispatch]
  );

  return (
    <div>
      <span>{value}</span>

      // May render unnecessarily due to the changed reference
      <MyIncrementButton onIncrement={dispatch} />

      // In callback, all fine
      <MyIncrementButton onIncrement={incrementCounter} />
    </div>
  );
};

Leave a Comment