Ref changes without a render request
Click Count twice, then Show. What does the console print, and when does the Show button’s label change?
Code Snippet
import { useRef, useState } from "react";
export default function App() {
const hits = useRef(0);
const [shown, setShown] = useState(0);
return <>
<button onClick={() => console.log(++hits.current)}>Count</button>
<button onClick={() => setShown(hits.current)}>Show: {shown}</button>
</>;
}Expected Output & Explanation
Console: 1, then 2
Show label: Show: 0 until Show is clicked, then Show: 2 Ref writes persist but do not request rendering. Show reads the current ref in an event handler and copies it into state, which updates the UI.
Module Context & References
React · Predict the behavior Trace state queues, stale snapshots, keys, effects and refs
Personal Notes · Markdown