Start learning free

LESSON 127 OF 161 · FRONTEND: FRONTEND WITH AI

The AI's Effect Never Stops in JavaScript

Practice

An AI assistant wrote the shop's product list with a category filter, in src/App.jsx. It loads the products in an effect: code React runs after it draws the component. In short, the AI's effect looks like this:

useEffect(() => {
  async function loadProducts() {
    // … fetch the products of the chosen category …
    setProducts(data);
  }
  loadProducts();
});

Look at the very end: });. The effect has no dependency array, so it runs after every draw. Its setProducts(data) gives React a new array, so React draws App again, which runs the effect again, which fetches again, without end. The page looks fine, but it keeps asking the API while the visitor just reads it (the check stops it).

The dependency array lists the changing values the effect reads. React runs the effect after the first draw, then again only when one of them changes. For example, an effect that writes the cart's size in the tab title:

useEffect(() => {
  document.title = count + " items";
}, [count]);

Your page must ask once when it opens and once when the visitor chooses a category:

> open the page
  request: GET /api/products -> 200
  screen:
    ...
        text: 8 products
> choose "kitchen" in "Category"
  request: GET /api/products?category=kitchen -> 200
  screen changes:
    ...
    -     text: 8 products
    +     text: 2 products

Your task: in src/App.jsx, write the effect again with [category] as its dependencies. Inside it, an async function loadProducts fetches /api/products?category= plus the category when one is chosen, else /api/products, and gives the answer's data to setProducts; the effect calls it.


Assignment
Follow the Coding Tutorial to rebuild the product list's effect so that it runs only when the page opens and when the category changes.


Hint
The effect reads category, so category goes in the array. Don't put products there: setProducts changes it after every answer, and the loop would come back.


STEP 1 OF 7
    Ctrl + Enter to check

    Aiui Effect Loop 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