Sub topic 4
The Problem: Two Components, Two Copies of the Truth
This chapter assumes you can write function components in JSX, pass props, call useState, and handle onChange events. It also assumes you know the basics of JavaScript destructuring and arrow functions. You don't need any knowledge of lifting state yet. This chapter is about the problem that makes lifting necessary.
What you will learn
- Why
useStategives each component instance its own private copy of a value. - Why two sibling components cannot share or synchronize that value on their own.
- How to recognize the symptom in real code.
- Why the common quick fixes make things worse.
Each instance owns its state
State declared with useState belongs to one component instance, not to the component function. The function is a template. Each time you render it in a different place in the tree, React creates a separate instance with its own state slot.
Here is a small component that renders a labeled text input and remembers what you typed.
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 "hello" into the First input. The Second input stays empty. Nothing is broken here, because this is how state is designed to work. The two Field elements run the same code, but each has its own text.
React keeps the state attached to the component's position in the tree. The Field labeled "First" is the first child of the fragment in App, and the one labeled "Second" is the second child. Each position has its own state slot, even though both use the identical function.
Why the siblings cannot sync themselves
Suppose the requirement is that both inputs always show the same text. The component above cannot meet it, and the reason is structural.
Firstcan read and write only its owntext. It has no reference to the state insideSecond.Secondhas the same limitation in the other direction.- Props flow downward, from parent to child. A sibling is not a parent, so there is no prop path between them.
- State is private. React offers no API for one component to reach into another's
useStateslot.
So the data has no route from one sibling to the other. The only component that both siblings share is their parent, App. Any solution has to involve that parent.
The diagram shows the core issue. There are two values named text, and they were never one value. Each is a separate source of truth for what its own input displays. When the two disagree, nothing in the program says which one is correct.
Recognizing the symptom
The sibling sync problem shows up in real applications in several forms. The names differ, but the shape is the same: two components display or depend on one fact, and each stores its own version of it.
| Situation | Where the copies live | What goes wrong |
|---|---|---|
| Two inputs for the same value, such as a temperature in Celsius and Fahrenheit | One `useState` in each input component | Editing one leaves the other stale |
| A list of items and a "total" badge elsewhere on the page | The list holds the items, the badge holds its own count | The badge shows an old number after an item is added |
| Two accordion panels where only one should be open | Each panel holds its own `isOpen` | Both can be open at once, because neither knows about the other |
| A search box and a results list | The box holds the query, the list holds a copy | The results do not match what the box shows |
The accordion case is a little different from the others. The two panels do not show the same value. Instead, a rule spans both of them: "at most one is open." A rule about a group cannot be enforced by any single member of the group, because each member only sees itself.
A tempting wrong fix: copying state with an effect
Developers who meet this problem often reach for a workaround. They try to keep the copies equal by watching one and writing to the other, usually with useEffect or a ref. This is the wrong direction. Look at what it requires.
- The siblings still have no way to talk to each other, so you need a channel such as a callback from the parent anyway.
- Once the parent is involved, the parent might as well hold the value directly.
- Syncing copies introduces an extra render. The first render shows the old value, then the effect runs, then a second render shows the new one. Users can see flicker, and your code has to reason about the in-between state.
- Two writers to one value invite loops. If A updates B and B updates A, you must add guards to stop it.
The root of the problem is the existence of two copies. Syncing them keeps both copies and adds machinery to hide that fact. A better approach removes one copy.
What "two copies of the truth" costs you
It helps to be precise about why duplicated state is harmful, since this motivates the next chapters.
- Disagreement is possible. If a value is stored in two places, there are states of the program where the two places differ. Every state your program can reach is one you must test and reason about. A single copy makes the disagreeing states impossible.
- Updates must be paired. Every code path that changes one copy must remember to change the other. The first time someone adds a new path and forgets, you have a bug that appears only in that path.
- Debugging has no authority. When two components show different values, you cannot tell which one is right without understanding the history of events that led there.
- Props cannot fix it. A value passed as a prop is read-only for the child. Passing a prop down does not make the child's separate
useStatefollow it, as the next section shows.
A related trap: copying a prop into state
A common half-step is for a child to receive a value as a prop and then use it as the initial value of its own state. This looks like sharing, but it is still two copies.
import { useState } from 'react';
function Field({ label, initial }) {
// initial is read once, on the first render only
const [text, setText] = useState(initial);
return (
<label>
{label}: <input value={text} onChange={e => setText(e.target.value)} />
</label>
);
}
export default function App() {
const [shared, setShared] = useState('hello');
return (
<>
<Field label="First" initial={shared} />
<Field label="Second" initial={shared} />
<button onClick={() => setShared('world')}>Set to world</button>
<p>Parent value: {shared}</p>
</>
);
}Click the button. The paragraph changes to "world", but both inputs still show "hello". React uses the argument to useState only on the first render of that instance. After that, the initial prop is ignored, and the input follows its own text. The parent has a value and each child has a separate one, so now there are three copies.
The shape of the solution
You do not need the full solution yet, but the diagnosis points at it. The pieces are:
- The shared fact should be stored once.
- It should live in a component that is an ancestor of every component that needs it. The closest common parent is the natural choice, because it can pass data down to both siblings.
- The children should stop owning that value. They receive it as a prop and render it.
- The children still need to change it, and props are read-only. So the parent also passes down a function, and the children call it to request a change.
After this change, there is one text, and both inputs are views of it. They cannot disagree because there is nothing for them to disagree with. This is the idea behind lifting state up, and the next chapters build it step by step: first the principle of a single source of truth, then the mechanics of moving the state.
Checking your understanding
Before moving on, make sure you can answer these without looking back.
- If you render the same component three times, how many state slots exist for its
useStatecall? - Which component is the first one that both siblings can share data through?
- Why does
useState(props.initial)fail to keep a child in sync with its parent?
Exercise
A page has a PriceInput component with its own useState for the price, and a separate PriceSummary component with its own useState for the price. Both are rendered inside Checkout. A teammate suggests adding a useEffect in PriceSummary that copies the price from somewhere. Explain why the two components show different prices, and why the effect is the wrong fix.
Show answer
Each component instance has its own state slot, so PriceInput and PriceSummary store two independent copies of the price. Neither can read the other's state, and they are siblings, so no props flow between them. An effect that copies one price into the other keeps both copies, adds an extra render with a stale value in between, and still needs a channel such as a callback from Checkout. Since Checkout is the closest common parent, the better fix is to keep one price there and pass it down. That leaves one copy, so the two components cannot disagree.
Exercise
In the second code example, Field receives initial={shared} and calls useState(initial). After clicking "Set to world", why do the inputs still show "hello"? How many separate copies of the text exist at that point?
Show answer
React uses the argument to useState only on the first render of each instance, so later changes to the initial prop are ignored. Each input follows its own text state, which is still "hello". There are three copies: the parent's shared (now "world") and one text in each Field (both "hello").
Exercise
An accordion has two Panel components, each with its own isOpen state, and the requirement is that opening one closes the other. Why can neither panel implement this rule alone?
Show answer
Each panel can see and change only its own isOpen. The rule involves both panels, so it needs a component that knows about both, which is their parent. The parent can store which panel is active, for example as one index, and tell each panel whether it is open.