Lift state only as far as it needs to go
Keep React state in the lowest component that needs it, and move it up only to the nearest parent of the components that share it.
When two siblings must show the same value, the state moves to their parent. The mistake is to keep going and put it in the app root, so the entire tree re-renders on each keystroke.
import { useState } from 'react';
function Results({ query }) {
return <p>Results for {query || 'nothing'}</p>;
}
function SearchBar({ query, onChange }) {
return <input value={query} onChange={(e) => onChange(e.target.value)} />;
}
export function SearchSection() {
const [query, setQuery] = useState('');
return (
<section>
<SearchBar query={query} onChange={setQuery} />
<Results query={query} />
</section>
);
}
export function App() {
return (
<main>
<Header />
<SearchSection />
<Footer />
</main>
);
}(type "ada") -> SearchSection re-renders, with SearchBar and Results
-> Header and Footer are not re-renderedquery is needed by SearchBar and Results, so their closest shared parent, SearchSection, owns it. A state change re-renders the component that owns the state and its children, so Header and Footer are not touched. If the state lived in App, they would be. See Sharing State Between Components.
Go up one level at a time, and only when a second component needs the value. If many distant components need it, that is when context or a store becomes the better tool.