Course contentsShow
← React
Lesson 2314 of 2,39650. Performance: Optimization TechniquesFree lesson

Before/After: State at Root vs State in Subtree

Concrete example showing render count reduction when state moves from App to a child component.

Before/After: State at Root vs State in Subtree

You'll learn: How moving state from the root to a child component can dramatically reduce the number of component re-renders in your app.

The Performance Impact of State Location

When state lives at the top of your component tree (like in App), every state update triggers a re-render cascade through all descendants—even those that don't use that state. By moving state down to the component that actually owns and uses it, you isolate re-renders to just that subtree.

Think of it like office announcements: broadcasting every message over a company-wide PA system forces everyone to listen, even if it only concerns the marketing team. Moving state down is like sending an email directly to marketing—only they're interrupted.

Before: State at Root

function App() {
  const [filter, setFilter] = useState('');
  // ❌ Filter state causes App + ALL children to re-render
  
  return (
    <>
      <Header />
      <Sidebar />
      <ProductList filter={filter} setFilter={setFilter} />
      <Footer />
    </>
  );
}

Every setFilter call re-renders Header, Sidebar, Footer—everything, even though only ProductList cares about filtering.

After: State in Subtree

function App() {
  return (
    <>
      <Header />
      <Sidebar />
      <ProductList /> {/* ✅ Manages its own filter state */}
      <Footer />
    </>
  );
}

function ProductList() {
  const [filter, setFilter] = useState('');
  // Only ProductList and its children re-render on filter changes
  
  return (/* ... */);
}

Now Header, Sidebar, and Footer never re-render when the user types in the filter box. Render count drops significantly.

Key Takeaway: Moving state closer to where it's actually used eliminates unnecessary re-renders in unrelated parts of your component tree—measure with the Profiler to see the difference.