Start learning free

LESSON 115 OF 161 · FRONTEND: ACCESSIBLE, FAST, CORRECT

Don't Recompute in JavaScript

Practice

Every time state changes, React calls your component again: a new draw. Every line in its body runs again. If one of those lines sorts a list, the list is sorted again on every draw, even when you only opened a panel and no product changed.

useMemo remembers. It runs a function, keeps what it returns, and runs it again only when a value in its dependency list changed:

const total = useMemo(() => {
  return addPrices(lines);
}, [lines]);

Here addPrices runs again only when lines changes. Memo has a cost too: it keeps the result and compares the dependencies on every draw. For quick work, like joining two strings, a plain line is simpler and just as fast.

The given sortByPrice prints a line each time it runs. Your page must print:

> open the page
  console.log: sort 1: sorting 0 products
  request: GET /api/products -> 200
  console.log: sort 2: sorting 8 products
  section "Products": 8 products, Pen $2 first, Gift card $50 last
> click "Cart"
  (no sort line: products and query didn't change)
> type "p" into "Search"
  console.log: sort 3: sorting 5 products
  text: 5 products

Your task: in src/App.jsx, make shown: the products whose name includes the search text, in any case, sorted by price, inside a useMemo that depends on products and query. Then draw a ProductList with it under the search field.


Assignment
Follow the Coding Tutorial to filter and sort the product list inside a useMemo, so opening the cart doesn't sort again.


Hint
The dependency array goes after the function, like in useEffect. Lower-case both the name and the query before includes.


STEP 1 OF 4
    Ctrl + Enter to check

    Perf Expensive Work in JavaScript

    Keep going with JavaScript1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free