Sub topic 2
Quick refresher: state belongs to a component
This chapter assumes you already know JavaScript functions, destructuring, and arrow functions. It also assumes you can write basic JSX and function components, pass props, call useState, and handle events such as onChange. Here we review how state is owned by a component. The rest of the tutorial relies on that idea.
What "belongs to a component" means
When a component calls useState, React stores the value for that specific instance of the component. It does not store it in the function, and it does not store it in a shared variable. The value is attached to the component's position in the rendered tree.
const [count, setCount] = useState(0);This line returns two things: the current value (count) and a function that schedules a new value (setCount). The argument 0 is used only on the first render of that instance. On later renders React ignores it and returns the stored value.
Three consequences follow from this ownership:
- Two instances of the same component each get their own state.
- State survives re-renders, because React keeps it between calls to the function.
- State is private. Other components cannot read or write it directly. They can only see what the owner chooses to pass down as props.
Each instance has its own copy
The first code example in this tutorial shows the consequence most clearly. The component Field is written once and rendered twice.
import { useState } from 'react';
function Field({ label }) {
const [text, setText] = useState('');
return (
<label>
{label}: <input value={text} onChange={e => setText(e.target.value)} />
</label>
);
}
export default function App() {
return (
<>
<Field label="First" />
<Field label="Second" />
</>
);
}Type into the first input and the second stays empty. Each Field has its own text. React tells the two instances apart by their position in the tree: the first Field is child 0 of the fragment, the second is child 1.
The diagram shows two boxes with separate values. There is no line between them, so there is no way for one to learn what the other holds. That gap is the problem the next chapters solve.
How a state update works
Calling the setter does not change the variable in the current render. It asks React to render the component again with a new value.
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
console.log(count); // still the old value in this call
}
return <button onClick={handleClick}>Clicked {count} times</button>;
}In the first click, console.log prints 0, even though the button then shows 1. Each render has its own snapshot of count. The handler closed over the snapshot from the render in which it was created.
This matters when you update state based on its previous value. If you call the setter several times in one handler, each call sees the same snapshot:
import { useState } from 'react';
export default function Triple() {
const [count, setCount] = useState(0);
function addThree() {
setCount(count + 1);
setCount(count + 1);
setCount(count + 1);
}
function addThreeCorrectly() {
setCount(c => c + 1);
setCount(c => c + 1);
setCount(c => c + 1);
}
return (
<>
<p>Count: {count}</p>
<button onClick={addThree}>+3 (wrong)</button>
<button onClick={addThreeCorrectly}>+3</button>
</>
);
}The first button adds 1, because all three calls sayset count to 0 + 1". The second button adds 3. A function passed to the setter is called an updater function. React queues it and passes in the latest queued value.
Do not mutate state
React decides whether to re-render by comparing the new value with the old one using Object.is. If you change an object or array in place and pass the same reference to the setter, React sees no change.
import { useState } from 'react';
export default function Profile() {
const [user, setUser] = useState({ name: 'Ada', age: 36 });
function birthdayBroken() {
user.age += 1; // mutates the existing object
setUser(user); // same reference, so React skips the update
}
function birthday() {
setUser({ ...user, age: user.age + 1 }); // new object
}
return (
<>
<p>
{user.name} is {user.age}
</p>
<button onClick={birthdayBroken}>Broken</button>
<button onClick={birthday}>Birthday</button>
</>
);
}Treat state as read-only. To change it, build a new object or array, using spread syntax, map, filter, or similar. This habit will matter later, because lifted state is usually an object or an index that several children depend on.
When state is kept and when it is reset
React keeps state for an instance as long as that instance stays in the same place in the tree. State is discarded when:
- The component is removed from the tree.
- The component's position changes in a way React cannot match, for example it moves to a different parent.
- The component's
keychanges.
import { useState } from 'react';
function Note() {
const [text, setText] = useState('');
return <input value={text} onChange={e => setText(e.target.value)} />;
}
export default function App() {
const [show, setShow] = useState(true);
return (
<>
{show && <Note />}
<button onClick={() => setShow(!show)}>Toggle</button>
</>
);
}Type something, click Toggle twice, and the input is empty again. The first click removed Note, which destroyed its state. The second click created a new instance with a fresh useState('').
This has a direct link to lifting state. If a piece of state must outlive a child, for example because the child can be hidden, the state cannot live in that child. It has to live in a component that stays mounted.
State is local, and that is both a strength and a limit
Local state has real advantages. A component that owns its state is easy to reason about, easy to move, and easy to reuse. You can render ten Field components without writing any coordination code.
The limit appears when two components must agree. Because state is private, Field cannot read its sibling's text, and a sibling cannot write to it. React data flows one way, from parent to child through props. There is no sideways path.
| Need | Where state can live | Works? |
|---|---|---|
| Only one component uses the value | That component | Yes |
| A component and its children use the value | That component, passed down as props | Yes |
| Two siblings use the same value | Inside either sibling | No, the other cannot reach it |
| Two siblings use the same value | Their closest common parent | Yes, covered next |
Quick checks before moving on
Use these questions to confirm the model is solid.
- If a component renders three times in one parent, how many separate state values exist for a single
useStatecall? Three, one per instance. - Does
setCount(count + 1)changecountin the current function call? No. It schedules a new render with a new snapshot. - Why does
setUser(user)after mutation do nothing? The reference has not changed. - What destroys a component's state? Unmounting it, or changing its
key.
If any answer surprises you, reread the matching section before continuing. The next chapters assume all four are second nature.
Common mistakes at this level
- Reading state right after setting it. The variable still holds the old value in that call. Compute the new value in a local variable if you need to use it immediately.
- Mutating objects and arrays. Always create a new value.
- Using a stale value for chained updates. Use the updater form
setX(x => ...). - Putting state in a child that can unmount. The state will disappear with it.
- Assuming same-looking components share state. They share code, not data.
Exercise
A parent renders <Counter /> twice. A user clicks the first counter three times. What does the second counter show, and why?
Show answer
It still shows its initial value (0). Each Counter instance has its own useState value, stored by React for that position in the tree. Clicking the first counter only updates the first instance's state.
Exercise
A handler runs setCount(count + 1); setCount(count + 1); when count is 5. What is count on the next render, and how would you make it 7?
Show answer
It becomes 6, because both calls use the snapshot value 5. To reach 7, use updater functions: setCount(c => c + 1); setCount(c => c + 1);.
Exercise
A tab panel with a text input is hidden and shown with {isOpen && <Panel />}, and the input keeps losing what the user typed. Where should the typed text be stored to prevent this, and why?
Show answer
In a component that stays mounted while the panel is hidden, such as the parent that controls isOpen. State inside Panel is destroyed when Panel unmounts. A parent that stays mounted keeps the value and can pass it down as a prop.