Reputation: 501
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
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:
setState
occurs (state: 1, ref: 0)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