Sub topic 3
Decide Where State Should Live
Assume you know basic JavaScript, HTML, JSX, and function components. The key question is not “which component needs this value?” It is “which components must share this value?”
Step 4: Put shared state in the closest common parent
filterText affects both the search box and the product table. inStockOnly does too. Their closest common parent is FilterableProductTable, so that component owns both pieces of state.
The table receives current values as props. The search box receives the same values and receives callback props to request changes.
Step 5: Add inverse data flow with callback props
React data normally flows downward, from parent to child. A child cannot directly change its parent’s state. Instead, the parent passes a function. The child calls that function when the user acts.
This is sometimes called inverse data flow: the event travels upward through a callback, while the updated value travels downward as a prop.
Controlled inputs
A controlled input gets its displayed value from React state. Its onChange handler reports the new value to the owner.
import { useState } from 'react';
function SearchBar({
filterText,
inStockOnly,
onFilterTextChange,
onInStockOnlyChange
}) {
return (
<form>
<input
value={filterText}
onChange={(event) => onFilterTextChange(event.target.value)}
placeholder="Search..."
/>
<label>
<input
type="checkbox"
checked={inStockOnly}
onChange={(event) => onInStockOnlyChange(event.target.checked)}
/>
Only show products in stock
</label>
</form>
);
}
export default function FilterableProductTable() {
const [filterText, setFilterText] = useState('');
const [inStockOnly, setInStockOnly] = useState(false);
return (
<SearchBar
filterText={filterText}
inStockOnly={inStockOnly}
onFilterTextChange={setFilterText}
onInStockOnlyChange={setInStockOnly}
/>
);
}Iterate and evaluate trade-offs
Keep a component when it has a clear responsibility. Combine very small components when splitting them adds indirection without improving reuse or clarity. Keep state as high as necessary for sharing, but no higher. This preserves predictable one-way data flow.
Exercise
Where should state live when two sibling components need to read and change it?
Show answer
In their closest common parent, with values passed down and callback props passed to the components that report changes.