Lifting State Up
When to lift
If two children need the same changing data, store it in their parent and pass it down as props.
Parent owns the state
Children receive values and callbacks; they do not keep duplicate copies.
function App() {
const [query, setQuery] = useState("");
return (
<>
<SearchBox query={query} onQueryChange={setQuery} />
<Results query={query} />
</>
);
}
Child calls the callback
The child asks the parent to update state.
function SearchBox({ query, onQueryChange }) {
return (
<input
value={query}
onChange={(e) => onQueryChange(e.target.value)}
placeholder="Search"
/>
);
}
Keep state close
Lift only as far as needed. State that one component uses alone can stay local.
Comments
One comment per signed-in account. Comments are saved with this page’s URL.