Sub topic 2
One Owner per Piece of State
Assume you know function components, JSX, props, useState, and event handlers. This chapter uses those ideas to keep related components synchronized.
One owner per piece of state
State is data that a component remembers between renders. When several components need the same data, give that data one owner. This owner is the component that stores the state and decides how it changes.
Two sibling components should not each store their own copy of the same value. Their copies can drift apart because each component updates independently. A single source of truth avoids that problem.
Lifting state to the closest common parent
Lifting state up means moving state from a child into the nearest parent shared by every component that needs it. The parent passes the current value down and passes a callback, or update function, down as well.
This preserves React’s one-way data flow: props move from parent to child, while children request changes by calling functions supplied by the parent.
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} />
</>
);
}App owns text. Both siblings receive the same value, so editing either field updates both.
Controlled inputs: the parent owns the value
A controlled input is an input whose displayed value comes from React state through its value prop. Its onChange handler sends new text back to the owner.
Keep input values as strings while the user edits them. Convert them to numbers only when calculation requires it. Otherwise, empty input and partially typed values can behave incorrectly.
When debugging, check that each controlled input has both value and onChange, and that the callback updates the state owned by the parent.
Exercise
Where should state live if two sibling inputs must always display the same text?
Show answer
In their closest common parent, which passes the value and an update callback to both inputs.