Leland
Leland

Reputation: 2129

How does React know hook-returned functions are stable?

In the React docs, it states:

The set function has a stable identity, so you will often see it omitted from Effect dependencies

The legacy docs also remark:

React guarantees that setState function identity is stable and won’t change on re-renders

We can indeed see this behavior in the following snippet, which will run the effect only once despite state changes causing the component to re-render.

const { useState, useEffect } = React;

function Counter() {
  const [count, setCount] = useState(0);

  // This effect will run only once because the identity of setCount doesn't change
  useEffect(() => {
    console.log("Effect ran!");
  }, [setCount]);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(c => c + 1)}>Increment</button>
    </div>
  );
}

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Counter />);
<div id="root"></div>

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/18.3.1/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/18.3.1/umd/react-dom.production.min.js"></script>

That this behavior exists has been talked about on SO before, like React Hooks: setState functionality on re-renders

My question is:

Upvotes: 0

Views: 28

Answers (0)

Related Questions