CodeBlanks Logo Icon CodeBlanks

Summary - useMemo

Wrap the filter and sort of a big list with useMemo.

Summary - useMemo

In this group you learned what useMemo is, the dependency check, and the pitfalls. Now you can safely cache expensive computations.

The recipe: wrap only genuinely slow computations in useMemo, write the dependency array completely, keep the function pure. These three steps make useMemo bring speed without harm.

In the next step you'll write a list component that both filters and sorts.

Practice Write FilterSortList

Complete the skeleton. Write a FilterSortList component. Take ({ '{ items, query }' }). Compute visible with useMemo(() => items.filter(i => i.name.includes(query)).sort((a, b) => a.name.localeCompare(b.name)), [items, query]). Inside <ul>, render visible.map(i => <li key={ '{ i.id }' }>{ '{ i.name }' }</li>). Export it.

Starter code

App.jsx
import { useMemo } from "react";

// Write the FilterSortList component here

Sample solution

App.jsx
import { useMemo } from "react";

function FilterSortList({ items, query }) {
  const visible = useMemo(
    () => items.filter((i) => i.name.includes(query)).sort((a, b) => a.name.localeCompare(b.name)),
    [items, query],
  );
  return (
    <ul>
      {visible.map((i) => (
        <li key={i.id}>{i.name}</li>
      ))}
    </ul>
  );
}

export default FilterSortList;

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 When should useMemo NOT be used?

  • For small computations Correct answer
  • For expensive computations
  • For big list filters
  • For complex computations

Explanation: Not for small computations.

2 Match the useMemo recipe

Term Meaning
expensive use
small don't
pure required
deps complete

All lessons in Intermediate