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's problem, where two sibling components each held their own copy of the same value.
The rule
Every piece of state should have exactly one owner, which is the component that calls useState for it. Every other component that needs the value receives it as a prop. This idea is called a single source of truth.
If two components each call useState for the same information, React treats them as two unrelated values. Nothing connects them, so they drift apart as soon as one changes. You can't fix that by copying one value into the other. You fix it by deleting one copy.
Moving ownership to the parent
Here is the earlier Field example after the fix. The Field components no longer call useState. App owns text and gives each child the current value and a function for requesting a change.
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} />
</>
);
}Data now moves in two directions, each with a clear job:
When you type in the first input, this sequence runs:
- The input's
onChangefires, andFieldcallsonChange(e.target.value). - That prop is
setText, soAppstores the new string. Appre-renders and passes the newtextto bothFieldcomponents.- Both inputs show the same text.
The child never changes the value itself. It only asks the owner to change it.
Ownership also enforces rules between components
Some rules involve more than one component, so no single component can enforce them alone. An accordion that opens one panel at a time is an example. If each panel kept its own isOpen flag, nothing could close the others. The parent instead stores one number, activeIndex:
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>
</>
);
}A single index can only point at one panel, so the "only one open" rule can't be broken. With two separate flags it could be.
Spotting a second owner
Duplicated ownership is easy to create by accident. Watch for these patterns:
| Pattern | Why it breaks | Fix |
|---|---|---|
| A child calls `useState` for a value its siblings also show | The copies diverge | Move the state to the common parent |
| A child copies a prop into state, as in `useState(value)` | React reads the argument only on the first render, so later prop changes are ignored | Use the prop directly |
| A parent and child both store the same flag | Two writers can disagree | Keep it in one place and pass it down |
The second pattern is the most common. This Field looks correct but ignores updates from its parent:
import { useState } from 'react';
function BrokenField({ value }) {
const [text, setText] = useState(value);
return <input value={text} onChange={e => setText(e.target.value)} />;
}After the first render, text belongs to BrokenField. If the parent later passes a different value, the input doesn't change.
Choosing the owner
Ask which component must know the value. The owner is the closest component that sits above every component that reads or changes it. The next chapter covers this step in detail.
Exercise
A page has a SearchBox that edits a query string and a ResultsList that filters items by the same query. Each component currently calls useState for its own query, and the list never updates. Where should the state live, and what does each child receive?
Show answer
Move the query state into the closest common parent, such as a SearchPage component. Pass SearchBox the current query and a setter as props, for example value and onChange. Pass ResultsList the query as a prop. SearchBox asks the parent to change the value, and the parent re-renders both children with the new query.