Sub topic 5
One owner per piece of state
This chapter assumes you can write function components, pass props, call useState, and handle onChange events. It builds on the previous chapter, where two sibling components each kept their own copy of the same text and drifted apart. Here you will learn the rule that fixes that problem, and how to apply it before you write any code.
The principle
A single source of truth means that every piece of data in your app has exactly one place where it is stored and changed. Every other place that needs the data receives it from that owner, usually as a prop.
React's data flow is built around this idea. State lives in a component. That component can pass the value down to its children as props. Children cannot reach up and change the parent's state directly. They can only call a function that the parent gave them.
The result is that for any value on screen, you can ask "who owns this?" and get one answer. If you cannot answer, or the answer is "two components", you have a bug waiting to happen.
Why two owners fail
Recall the Field example from the previous chapter. Each Field calls useState(''), so each one has its own slot in React's memory. Typing in the first input calls the first setText. The second component never learns about it.
Nothing in React is broken here. Two useState calls create two independent values. The code only looks like it describes "the text" because both inputs were given similar names and similar markup.
There are three common ways to end up with two owners:
- Two sibling components each call
useStatefor data that should be shared. - A child copies a prop into its own state, such as
useState(props.value), so the copy stops following the prop. - A parent stores a value and also stores something calculated from it, and the two are updated in separate steps.
All three fail the same way. Two values are supposed to agree, and the code relies on every update remembering to change both.
Finding the owner
To decide who owns a piece of state, follow these steps. They are the working version of the principle.
- List every component that displays or changes the value.
- Find the closest component that contains all of them in the tree.
- Put
useStatein that component. - Pass the value down as a prop to each component that displays it.
- Pass a function down as a prop to each component that changes it.
Step 2 matters. If the owner is higher than it needs to be, state changes re-render more of the tree than necessary, and unrelated components receive props they do not use. If the owner is lower than the closest common parent, some component cannot reach the value. A later chapter covers the trade-offs of choosing the owner. For now the rule is: the closest common parent.
The owner in code
Here is the fixed version of the earlier example. App is the closest common parent of both fields, so App owns text.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function App() {
const [text, setText] = useState('');
return (
<>
<Field label="First" value={text} onChange={setText} />
<Field label="Second" value={text} onChange={setText} />
</>
);
}Field no longer calls useState. It has become a display of a value it does not own, plus a way to ask for a change. The flow of one keystroke looks like this:
Three things to notice:
- Data moves down through
value. Requests to change move up throughonChange. setTextis passed directly as the callback. It accepts the new string, which is exactly whatonChange(e.target.value)supplies.- Both fields read the same variable during the same render, so they cannot disagree. There is no moment where one has the new text and the other has the old one.
Ownership applies to every kind of value
The accordion from the topic plan shows that "one owner" is not only about text. Consider two panels where opening one must close the other.
import { useState } from 'react';
function Panel({ title, isActive, onShow, children }) {
return (
<section>
<h3>{title}</h3>
{isActive ? <p>{children}</p> : <button onClick={onShow}>Show</button>}
</section>
);
}
export default function Accordion() {
const [activeIndex, setActiveIndex] = useState(0);
return (
<>
<Panel
title="About"
isActive={activeIndex === 0}
onShow={() => setActiveIndex(0)}
>
Text about the project.
</Panel>
<Panel
title="Details"
isActive={activeIndex === 1}
onShow={() => setActiveIndex(1)}
>
More details here.
</Panel>
</>
);
}If each panel kept its own isOpen boolean, you would need panels to tell each other to close. That is two owners of one fact: "which panel is open". With a single activeIndex in the parent, the fact is stored once. A panel is open when its index equals activeIndex, so at most one panel can ever be open. The rule "only one open at a time" is enforced by the shape of the data, not by extra code.
Compare the two designs:
| Design | State stored | Can two panels be open? | Code needed to prevent it |
|---|---|---|---|
| One boolean per panel | `isOpen` in each panel | Yes | Extra coordination between panels |
| One index in the parent | `activeIndex` in `Accordion` | No | None |
When you can pick a data shape that makes invalid states impossible, prefer it.
Spotting a second owner in review
These patterns usually mean a value has two owners. Look for them when you read code.
useState(props.something)in a child, where the child is meant to follow the parent. The initial value is copied once. Later changes to the prop are ignored.- A
useEffectwhose only job is to call a setter when another value changes. This often means state is being copied from one place to another. - Two
useStatecalls whose values must always match, or where one is always calculated from the other. - A callback prop that sends data to the parent, which then stores it, while the child also keeps the same data.
The next example shows the first pattern. It looks harmless and fails quietly.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
function CopiedField({ label, value }) {
const [text, setText] = useState(value);
return <Field label={label} value={text} onChange={setText} />;
}
export default function App() {
const [text, setText] = useState('');
return (
<>
<Field label="Source" value={text} onChange={setText} />
<CopiedField label="Copy" value={text} />
</>
);
}Type in "Source" and the "Copy" input does not change. CopiedField read value once, on its first render, and kept its own text from then on. The prop keeps changing, but nothing reads it. The fix is to delete the state in CopiedField and use the prop directly, with an onChange prop for changes.
Edge cases
Not all state needs to be shared. If only one component reads and changes a value, such as whether a dropdown is open, it should keep the state locally. Lifting it adds props and re-renders for no benefit. Apply the rule only to values that more than one component needs.
Shared does not mean global. The owner is the closest common parent, not the root of the app. Putting everything in App makes every change re-render a large part of the tree and makes App hard to read.
A value you can calculate is not a second owner, if you calculate it. Storing fahrenheit in state when you already store celsius creates two owners. Calculating fahrenheit during render from celsius creates none. The temperature converter in a later chapter uses this approach.
Updates are requests. A child calls onChange, but the parent decides what to do. It can store the value, change it, or ignore it. This is what lets the owner enforce rules, such as limiting input length, in one place.
import { useState } from 'react';
function Field({ label, value, onChange }) {
return (
<label>
{label}: <input value={value} onChange={e => onChange(e.target.value)} />
</label>
);
}
export default function LimitedFields() {
const [text, setText] = useState('');
function handleChange(next) {
if (next.length <= 10) setText(next);
}
return (
<>
<Field label="First" value={text} onChange={handleChange} />
<Field label="Second" value={text} onChange={handleChange} />
</>
);
}Both inputs stop accepting characters after ten, and neither Field contains any rule about length. The rule lives with the owner.
Summary of the rule
Each piece of state has one owner. The owner is the closest component that contains everything that needs the value. It passes the value down as props and passes a change function down as a callback. Anything that can be calculated from existing state is calculated during render and is not stored again.
Exercise
A Price component shows a number it receives as a prop amount, and starts with const [value, setValue] = useState(amount). The parent changes amount from 10 to 20, but Price still shows 10. Explain why, and describe how to fix it so the parent owns the value.
Show answer
useState(amount) uses amount only on the first render. After that, React keeps the stored value, and later changes to amount are ignored. This makes two owners: the parent's amount and the child's value. To fix it, remove the state from Price and render amount directly. If Price must let the user edit the number, add an onChange prop and have the parent call its own setter and pass the new value back down as amount.
Exercise
Two components, Cart and Header, both need the item count, and both are children of Shop. Where should the count live, and what does Shop pass to each?
Show answer
The count lives in Shop, the closest common parent. Shop passes the count as a prop to both Cart and Header. If either component can change the count, Shop also passes it a callback such as onAdd or onRemove that calls the setter.