Derived State: Calculate, Don't Store

Filter a list from the search text on every render instead of keeping a second copy in state.

React · intermediate · 6 min · 20 steps · free

What you'll learn

DerivedState.jsx

import { useState } from 'react';

const FRUITS = ['Apple', 'Apricot', 'Banana', 'Cherry'];

export default function FruitSearch() {
  const [query, setQuery] = useState('');
  const visible = FRUITS.filter((f) => f.toLowerCase().startsWith(query));

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Search" />
      <p>
        {visible.length} of {FRUITS.length}: {visible.join(', ')}
      </p>
    </div>
  );
}

Step by step

  1. React renders <FruitSearch> for the first time: it calls the FruitSearch function.
  2. useState runs for the first time, so React stores the starting value for query and returns it: "".
  3. For f = "Apple", the callback returns true.
  4. For f = "Apricot", the callback returns true.
  5. For f = "Banana", the callback returns true.
  6. For f = "Cherry", the callback returns true.
  7. visible holds every fruit while the query is empty.
  8. FruitSearch returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  9. React turns the JSX into real page elements and shows them: look at the Screen panel.
  10. You type “ap” into the input. React calls its onChange handler.
  11. setQuery(e.target.value) does not change query right away: React queues the update and will render again. In this call query is still "".
  12. React renders <FruitSearch> again (render 2): it calls FruitSearch once more, from the top.
  13. useState returns the value React has kept for query: "ap". The starting value is only used on the first render.
  14. "apple" starts with "ap": true.
  15. For f = "Apricot", the callback returns true.
  16. "banana" does not: false.
  17. For f = "Cherry", the callback returns false.
  18. visible = ["Apple", "Apricot"], worked out fresh in this render.
  19. FruitSearch returns JSX: a description of what the screen should show, <div>…</div>. React has not changed the page yet.
  20. The page lists 2 of 4. One piece of state, query, drives everything.

Common mistakes

Best practices

Key takeaways

Check yourself

fullName from first and last: state or calculation?

Answer: Calculation

Problem with storing visible in state?

Answer: It can get out of sync with query

·

More in How Rendering Works