Navigate
Search topics, hooks, and fundamentals
Regular variables are created and destroyed on every render. This is the #1 gotcha for React beginners.
When React re-renders your component, it calls your function again from the top. Any variable declared with let or const is re-created with its initial value. Your previous changes? Gone.
function Counter() {
let count = 0; // runs every render → always 0
function handleClick() {
count = count + 1; // changes the local variable...
console.log(count); // logs 1, 2, 3 ...
}
return <span>{count}</span>; // but React already read 0
}Click the button. The display value is stuck at 0 because let count = 0 runs on every render. The actual clicks are tracked with a ref so you can see the difference.
Display value
0
let count = 0 (resets!)
Actual clicks
0
useRef (persists)
This is exactly why useState exists. It stores the value outside the function so it survives re-renders.
function Counter() {
// React stores this OUTSIDE the function
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1); // tells React → schedule re-render
}
return <span>{count}</span>; // shows the latest value
}Key takeaway:
useState persists values across rendersuseRef also persists values, but without triggering re-renders