Sub topic 1
Why a local variable is not enough
Prerequisites
This chapter assumes you know JavaScript functions, arrow functions, destructuring, and spread syntax. You should also be able to read basic JSX, write a function component, and pass props to it.
The problem: a counter that does not count
A component is a function that React calls to get a description of the screen. Each call is a render. Any local variable you declare inside the function is created fresh on every render.
Here is a first attempt at a click counter that uses a plain variable:
function BrokenCounter() {
let count = 0;
function handleClick() {
count = count + 1;
console.log('count is now', count);
}
return (
<button onClick={handleClick}>
Clicked {count} times
</button>
);
}Click the button and the console prints count is now 1, then count is now 2. The label still says Clicked 0 times. Two separate problems cause this.
Two reasons the variable fails
- Changing a local variable does not trigger a render. React only re-runs your component when it is told something changed. Assigning to
counttells React nothing, so the screen is never updated. - Local variables do not survive a render. Even if a render did happen, React would call
BrokenCounteragain. That call runslet count = 0again, and the earlier value is gone.
The next diagram shows the flow.
What state provides
A component needs two things that a local variable cannot give it:
- Memory between renders. A value that React keeps outside your function and hands back on each call.
- A trigger. A way to change that value that also tells React to render again with the new value.
State supplies both. The useState Hook is how a function component asks React for it. The next chapter shows how to declare it.
Common errors to watch for
- Declaring
letinside a component and expecting it to persist. - Mutating a variable in an event handler and expecting the screen to change.
- Moving the variable outside the component to make it persist. This makes every instance of the component share the same value.
Exercise
In BrokenCounter, the console shows the count rising but the screen always shows 0. Name the two reasons.
Show answer
First, assigning to a local variable does not tell React to re-render, so the screen is never updated. Second, local variables are re-created on every render, so any new render would reset count to 0.
Exercise
Why does moving let count = 0 outside the component not fix the problem?
Show answer
The value would persist, but changing it still does not trigger a render. It would also be shared by every instance of the component.