Start learning free

LESSON 91 OF 161 · FRONTEND: REACT EFFECTS AND DATA

Your Own Hook

Practice

App has grown long: the products, the loading flag, the error and the effect that loads them all sit inside it. You can move them into a hook of your own: a plain function whose name starts with use, that calls React's hooks (useState, useEffect) and returns what the component needs. The state still belongs to the component that calls the hook, and a change still makes that component draw again.

A tiny hook on another value:

function useToggle(start) {
  const [on, setOn] = useState(start);
  function toggle() {
    setOn(!on);
  }
  return { on, toggle };
}

// in a component:
const { on, toggle } = useToggle(false);

App already calls useProducts(category) and takes products, loading, error and reload out of what it returns. The file src/useProducts.js already has the loadProducts function, but no state, no effect and no return, so for now App gets undefined and the page stays empty. When the hook is done, Check prints the same as before the move (it makes the API fail once):

> the API will answer GET /api/products with 500
> open the page
  request: GET /api/products -> 500
  alert: Can't load the products
  button: Try again
> click "Try again"
  screen while waiting: text: Loading products…
  answer: GET /api/products -> 200
  text: 8 products
> choose "kitchen" in "Category"
  request: GET /api/products?category=kitchen -> 200
  text: 2 products

Your task: in src/useProducts.js, give useProducts its three pieces of state, a return with the four names App reads, and an effect that calls loadProducts at the start and whenever category changes.


Assignment
Follow the Coding Tutorial to build the useProducts hook in src/useProducts.js: its state, its return and its effect.


Hint
The hook returns an object. reload is the function loadProducts itself, written without parentheses, so App can hand it to the "Try again" button.


STEP 1 OF 6
    Ctrl + Enter to check