Sub topic 8
Props versus state: who owns the data
This chapter assumes you can write a function component, use useState at a basic level, and pass props with JSX attributes. It also assumes you know that a state setter triggers a re-render. The goal is a working rule for deciding where each piece of data lives.
The core difference
Props and state are both plain JavaScript values that a component uses while rendering. They differ in who controls them.
- Props are inputs. A parent decides them. The child reads them and cannot change them.
- State is memory. A component declares it with
useStateand changes it only through the setter function.
The same value can be state in one component and a prop in another. A parent holds likes as state. It passes likes to a child as a prop. For the child, the value is read-only input. For the parent, it is data it owns and can update.
| Question | Props | State |
|---|---|---|
| Who sets the value? | The parent component | The component that declares it |
| Can the component change it? | No | Yes, through the setter |
| What happens when it changes? | Happens when the parent re-renders with new values | Setter call schedules a re-render |
| Survives re-renders? | Replaced by whatever the parent passes | Yes, React keeps it between renders |
| Typical use | Configuration, data to display, callbacks | Form input, toggles, counters, fetched results |
Ownership as a design rule
Each piece of changing data should have one owner. The owner is the component that declares the state. Every other component that needs the value receives it as a prop. Every component that needs to change it receives a callback prop that asks the owner to do so.
This gives you a one-way flow. Data moves down through props. Requests to change data move up through callbacks. You can trace any value by walking up the tree until you find the useState call that owns it.
Lifting state up to share data
Suppose two sibling components need the same value. A search box needs the current query, and a list needs it to filter. Siblings cannot pass props to each other, and each keeping its own copy would let them disagree. The fix is to move the state to their closest common parent. This is called lifting state up.
import { useState } from 'react';
const FRUITS = ['Apple', 'Banana', 'Cherry', 'Grape', 'Pineapple'];
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={(event) => onQueryChange(event.target.value)}
placeholder="Search fruit"
/>
);
}
function FruitList({ query, fruits }) {
const needle = query.toLowerCase();
const visible = fruits.filter((fruit) => fruit.toLowerCase().includes(needle));
return (
<ul>
{visible.map((fruit) => (
<li key={fruit}>{fruit}</li>
))}
</ul>
);
}
export default function FruitSearch() {
const [query, setQuery] = useState('');
return (
<div>
<SearchBox query={query} onQueryChange={setQuery} />
<FruitList query={query} fruits={FRUITS} />
</div>
);
}FruitSearch owns query. SearchBox is a controlled component: it has no state of its own, so the input always shows whatever query says. When the user types, onQueryChange runs, the parent updates, and both children re-render with the new prop. There is exactly one copy of the query, so the box and the list cannot disagree.
Note that setQuery is passed directly as the callback prop. A setter is a function that takes the new value, so no wrapper is needed.
Deciding where state should live
Use this sequence when you add a piece of data:
- Can it be computed from props or other state? If so, do not store it. Compute it during render.
- Does it change over time because of user input or a response? If not, it is a constant or a prop.
- Which components render something based on it? Find their closest common parent.
- Put the
useStatecall in that parent. Pass the value and a callback down.
Keep state as low in the tree as the rule allows. State placed too high causes extra re-renders and forces you to pass props through components that do not care about them. State placed too low forces you to duplicate it.
Do not copy props into state
The most common mistake at this level is initializing state from a prop and expecting it to stay in sync.
import { useState } from 'react';
function PriceTag({ price }) {
// Wrong: the initial value is read once, on the first render only.
const [shown, setShown] = useState(price);
return <span>${shown}</span>;
}useState(price) uses its argument only on the first render. If the parent later passes a different price, shown keeps the old value. The component now has two sources of truth, and they have drifted apart. The fix is to read the prop directly, or to compute from it:
function PriceTag({ price, taxRate }) {
const total = price * (1 + taxRate);
return <span>${total.toFixed(2)}</span>;
}total is not state, because it is fully determined by the props. It recalculates on every render, which is cheap and always correct.
Copying a prop into state is acceptable in one case. The prop is explicitly only a starting value, and the component then owns the data. Name it to say so, for example initialCount, and expect later changes to the prop to be ignored.
import { useState } from 'react';
function Counter({ initialCount = 0 }) {
const [count, setCount] = useState(initialCount);
return <button onClick={() => setCount(count + 1)}>Clicked {count} times</button>;
}Resetting state when the identity changes
Sometimes a component owns state but should start over when its input changes. Think of an edit form that shows a different user. React keeps state attached to a component's position in the tree. If <UserForm user={user} /> stays in the same position and user changes, the old draft remains.
Give the component a key that identifies the thing it represents:
import { useState } from 'react';
function UserForm({ user }) {
const [draftName, setDraftName] = useState(user.name);
return (
<input value={draftName} onChange={(event) => setDraftName(event.target.value)} />
);
}
export default function Editor({ user }) {
return <UserForm key={user.id} user={user} />;
}When user.id changes, React discards the old UserForm and its state, then mounts a new one with the new initial value. This is usually clearer than syncing state with an effect.
Never mutate props
Props arrive as the same objects the parent holds. Changing them in the child changes the parent's data without telling React, so no re-render happens and the UI goes stale. Copy first, then ask the owner to apply the change.
function TodoItem({ todo, onToggle }) {
// Wrong: todo.done = !todo.done;
return (
<li>
<label>
<input
type="checkbox"
checked={todo.done}
onChange={() => onToggle(todo.id)}
/>
{todo.text}
</label>
</li>
);
}The parent's onToggle builds a new array with a new object for the changed item and passes it to its setter. The same rule applies to state: never mutate an array or object in state. Always pass the setter a new value.
Common errors
- Two copies of one value. A parent and child each hold the same data in state. Pick one owner and pass the value down.
- Stale derived state. A value computed from props is stored in state and goes out of date. Compute it during render instead.
- State too high. A frequently changing value, such as input text, lives at the top of the app and re-renders everything. Move it to the lowest component that needs it.
- Missing callback. A child needs to change the parent's data but has no way to ask. Add a callback prop named for the event, such as
onSelectoronQueryChange. - Setter used as a value. Writing
onClick={setOpen(true)}calls the setter during render. WriteonClick={() => setOpen(true)}.
Exercise
A Cart component holds items in state. It renders <Summary items={items} />, and Summary has const [count, setCount] = useState(items.length) to display the number of items. After the user adds an item, the summary still shows the old count. Why, and how do you fix it?
Show answer
useState(items.length) uses its argument only on the first render, so count is a copy that never updates when the items prop changes. Remove the state and compute the value during render with const count = items.length;. The count is derived from a prop, so it should not be stored.
Exercise
Two sibling components, ColorPicker and Preview, both need the selected color. Where should the color state live, and what must you pass to each component?
Show answer
Put const [color, setColor] = useState('red') in their closest common parent. Pass color and onColorChange={setColor} to ColorPicker, and pass color to Preview. The parent is the only owner, so the two siblings always show the same value.