Sub topic 1
Why a local variable is not enough
Components often need to remember something between renders: a count, the text in an input, whether a menu is open. This chapter shows why an ordinary local variable cannot do that job, and what React provides instead. The next chapters cover the useState API itself. Here the goal is to understand the problem it solves.
Prerequisites
This chapter assumes you know the following:
- JavaScript functions, arrow functions, and destructuring.
- Basic JSX and how to write a function component.
- How to pass props to a component.
- How an event handler such as
onClickis attached in JSX.
You do not need to know any Hooks yet.
A counter that does not count
Start with the most natural attempt at a click counter. It keeps the count in a local variable and changes it in an event handler.
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 three times. The console prints count is now 1, then 2, then 3. The button still says "Clicked 0 times".
Two separate things go wrong here. They are worth separating, because each one is a reason that state is needed.
- Local variables do not survive a render. Each time React renders the component, it calls the function again from the top.
- Changing a local variable does not trigger a render. React has no way to know that
countchanged, so it never calls the function again and never updates the screen.
Reason 1: every render starts fresh
A function component is a plain JavaScript function. React renders it by calling it. When the function returns, its local variables are gone. The next call creates a new count and sets it to 0 again.
You can see this without any clicking. Suppose the parent re-renders and calls BrokenCounter a second time. The second call has no access to anything the first call did.
function Demo() {
let renders = 0;
renders = renders + 1;
console.log('renders in this call:', renders);
return <p>Rendered</p>;
}No matter how many times React renders Demo, the log always prints renders in this call: 1. Each call is independent.
A variable declared outside the component would survive, but that creates a different problem, covered later in this chapter.
Reason 2: changing a variable does not update the screen
Even if the value did survive, React would not know to show it. React updates the screen in three steps:
- Trigger. Something tells React that a component may need to change.
- Render. React calls your component function to get the new JSX.
- Commit. React applies the differences to the page.
Assigning to a local variable is not a trigger. It is only a JavaScript assignment. React is not watching your variables. It will only render again when it is told to, or when its parent renders.
So a working piece of component memory needs two features:
- A place to store the value that lives outside the function call and persists across renders.
- A way to change the value that also tells React to render again.
What state provides
React's answer is the state variable. It is created with the useState Hook. A Hook is a special function, whose name starts with use, that lets a component use a React feature.
useState gives you exactly the two missing features:
| Need | What `useState` returns |
|---|---|
| A value that persists between renders | The current state value |
| A way to change it and trigger a render | A setter function |
Here is the same counter written correctly.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Each click now calls setCount. React stores the new value, calls Counter again, and useState returns the updated count on that call. The button text changes.
You will look at this API in detail in the next chapter. For now, notice the shape: a pair of a value and a setter, returned by one call.
Where the value actually lives
If the function runs again from the top, how does useState(0) return something other than 0 on the second render?
The value is stored by React, not by your function. React keeps it in an internal record attached to that component's position in the tree. On the first render, useState(0) saves 0 into that record and returns it. On later renders, the argument is ignored and useState returns whatever is saved.
This is also why each component instance has its own state. Two Counter components on one page each have their own record, so clicking one does not change the other.
Why not use a variable outside the component?
A module-level variable survives between renders, so it looks like a fix for the first problem.
let count = 0;
function SharedCounter() {
function handleClick() {
count = count + 1;
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}This has two flaws:
- It still does not trigger a render, so the screen stays stale until something else causes a render. Then it suddenly jumps to the new value, which is confusing.
- It is shared by every instance of the component. If you render
SharedCountertwice, both buttons read and write the same variable.
State avoids both: it triggers renders, and it is private to each component instance.
A related shortcut is useRef, which also survives renders but deliberately does not trigger them. It is meant for values that are not shown on screen. If the value appears in your JSX, you almost always want state.
Common mistakes at this stage
- Expecting a local variable to "stick". If a value must outlive one render, it cannot be an ordinary
let. - Mutating a variable and expecting the UI to follow. Use the setter so React knows to render.
- Using a module-level variable to share data. It will be shared across instances and will not update the screen.
- Using state for everything. If a value can be computed from props or other state during render, it does not need its own state. That topic comes up in a later chapter.
Summary of the idea
A component function is called again for every render, so its local variables reset. Changing a local variable also does not tell React to render. State fixes both: React stores the value outside the function call, and the setter schedules a new render. The rest of this tutorial builds on that one mechanism.
Exercise
A component declares let clicks = 0; inside its body and increments it in a click handler. The console shows the number going up, but the screen always shows 0. Name the two reasons this happens and the Hook that fixes both.
Show answer
First, the function runs again on every render, so clicks is recreated as 0 each time and any earlier value is lost. Second, assigning to a local variable does not tell React to render, so the screen is never updated. The useState Hook fixes both: React stores the value between renders, and the setter function it returns schedules a re-render.
Exercise
You move let count = 0; outside the component to the top of the file so it survives renders. You render two copies of the component and click the first one. What problems remain?
Show answer
The screen still does not update when the variable changes, because assigning to it does not trigger a render. Also, both copies share the same module-level variable, so they cannot hold separate values. State is private to each component instance and triggers renders.