Skip to content
jshacks.dev
Frameworks

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.

1 min read
Summarize in AI

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.

src/Search.jsxJSX
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>
  );
}
Text
(type "ada")  -> SearchSection re-renders, with SearchBar and Results
              -> Header and Footer are not re-rendered

query 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.

Taggedreact 19
Share

More snippets

Frameworks

Update state from the previous value

Pass an updater function to the React state setter when the next value depends on the last one, so batched updates do not overwrite each other.

1 min read
Frameworks

Manage state with useState

Keep a changing value in a React 19 component with useState, and see why the setter schedules a re-render instead of changing the variable.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.