useRef without re-rendering
Some values need to survive a re-render but never change what you see. A click
count you only log, a timer id you need to cancel later, the previous value of a
prop. Put those in useState and the screen updates for no reason.
useRef gives you a box that lives across renders:
const clicks = useRef(0);
It returns a plain object with a single property, current. React creates that
object once and hands you the same object on every render, so
clicks.current keeps its value. You can read and write it whenever you like.
The part that catches people: changing current does not re-render the
component. React has no idea the value moved, so the screen keeps showing
whatever it rendered last.
function handleClick() {
clicks.current += 1; // no re-render
}
That is the trade. Use a ref for values you never show; use state when the value is shown on screen. If you find yourself wanting the UI to update, you wanted state.
Your job is to count clicks in a ref inside App.jsx, so the label does not
change.
Challenge
Some values should change without touching the screen. Export an App component
from App.jsx that counts clicks in a ref and shows a button labelled
Clicks: 0.
The Test clicks your button once, then checks the label still reads Clicks: 0 —
changing a ref does not re-render. The starter counts with state, so its label
changes and the Test fails.