HJW
HJW

Reputation: 501

How to understand the useRef in react

export default function App() {
  const [count, setCount] = useState(0);
  const countRef = useRef();
  useEffect(() => {
    countRef.current = count; //count one
    console.log("count: ", count); // count two
  }, [count]);
  return (
    <div className="App">
      <div>count: {count}</div>
      <button onClick={() => setCount(count + 1)}>+</button>
      <div>pre count: {countRef.current}</div>
    </div>
  );
}

I'm a little confused. When I click the button, print 1 and countRef.current is 0. Why the printed count and the assigned count are not the same value?

Upvotes: 0

Views: 417

Answers (1)

DBS
DBS

Reputation: 9994

In the background, the count state and the countRef are being kept almost exactly in sync, however the render happens between the state's update and the ref's update, which causes them to appear out of sync in the UI.

This is what's happening step by step:

  • The initial render (state: 0, ref: 0)
  • Button is clicked, setState occurs (state: 1, ref: 0)
  • The state changing triggers a render (state: 1, ref: 0) The screen now shows these values.
  • After the render, the effects are run (state: 1, ref: 1)
  • Updating a ref doesn't trigger a re-render, so you are left with the (state: 1, ref: 0) that was previously rendered in the UI, while the data behind the scenes is now (state: 1, ref: 1)

Upvotes: 2

Related Questions