Ritenta

Where should React state live?

Place each piece of state near the components that need to coordinate, and derive what you can.

Published: 2 min read

When two components disagree about the same selection, the problem is often duplicated ownership. A filter bar has one category in its local state while a result count stores another. Changing one does not reliably update the other. For each piece of state, choose one owner and let other components receive its value or a callback. React calls this a single source of truth for each state value.

Move state only as far as coordination requires

Imagine a product list with a filter control and a result count. Both need the chosen category, so the closest shared parent owns it. The filtered list and count can be calculated during render; storing copies would create extra synchronization work.

Long code lines scroll sideways →
import { useState } from 'react';

function ProductView({ products }) {
  const [category, setCategory] = useState('all');
  const visible = products.filter(
    (product) => category === 'all' || product.category === category,
  );

  return (
    <section>
      <select value={category} onChange={(event) => setCategory(event.target.value)}>
        <option value="all">All categories</option>
        <option value="books">Books</option>
        <option value="tools">Tools</option>
      </select>
      <p>{visible.length} matching products</p>
      <ul>{visible.map((product) => <li key={product.id}>{product.name}</li>)}</ul>
    </section>
  );
}

There is no need to move a tooltip's open state into the page if only the tooltip uses it. Conversely, a filter that must survive sharing or reload may belong in the URL; remote product data may belong in a server-state cache. The owner follows the feature's lifetime and consumers, not a rule that “all state goes global.”

Look for impossible combinations

If a view tracks isLoading, hasError, hasResults and isEmpty as independent booleans, it can enter contradictory states. Model the actual phases, then derive display decisions. React's state-structure guide recommends avoiding redundant and contradictory state.

For a practical check, draw the component tree and mark who reads and who changes each value. If two branches must agree, lift ownership to their closest shared point. If a value is computed from props or another state value, remove the duplicate and calculate it instead.