Stop 09 · React Hooks, Routing & StylingTopics · 1/8

useEffect Hook

Part of the MERN Stack Roadmap

In short

Rendering should only describe what the screen looks like. Fetching products, starting a timer or listening to window resize all happen outside React, and useEffect is the safe place to do them.

useEffect runs code after render to sync with things outside React, such as fetching data, setting timers or subscribing to events, and can clean up when the component unmounts.

The jaadu rolls up the metal shutter of a small shop and reaches for the light switch, while a ceiling fan waits to spin above the counter.

Think of it like this

Switching on the shop lights

A shopkeeper in Jaipur opens the shutter (render), then switches on the lights and the fan (the effect). At night, before locking up, he switches them off (the cleanup). If he moves to a new shop, he switches off the old one before opening the new one. useEffect follows the same routine every time its dependencies change.

Watch it happen

The life of an effect

Render
Paint screen
Run effect
Deps change
Cleanup

1/5React calls your component and gets JSX. No effects run during this step.

The big ideas

What you need to know

The dependency array

No array: runs after every render. []: runs once after mount. [category]: runs when category changes.

Return a cleanup

Return a function to clear timers, remove listeners or abort requests. React calls it before re-running and on unmount.

Async inside, not outside

The effect function itself cannot be async. Define an async function inside it and call it.

Not every calculation needs an effect

If a value can be computed from props or state during render, like a filtered list, compute it directly. Effects are for syncing with the outside world.

How it works

Writing a data-fetching effect

  1. 1

    Pick the trigger

    Decide which values should cause a refetch, such as category or page.

  2. 2

    Create a controller

    An AbortController lets you cancel the request if the trigger changes.

  3. 3

    Fetch and set state

    Await the response, check res.ok, then store the data.

  4. 4

    Handle errors

    Ignore AbortError, store real errors so the UI can show them.

  5. 5

    Clean up

    Return () => controller.abort() so old responses never overwrite new ones.

See it in code

Walk through the code

jsx
1import { useEffect, useState } from "react";2 3export default function ProductGrid({ category }) {4  const [products, setProducts] = useState([]);5  const [loading, setLoading] = useState(true);6  const [error, setError] = useState(null);7 8  useEffect(() => {9    const controller = new AbortController();10 11    async function load() {12      setLoading(true);13      setError(null);14      try {15        const res = await fetch("/api/products?category=" + encodeURIComponent(category), {16          signal: controller.signal,17        });18        if (!res.ok) throw new Error("Server returned " + res.status);19        const data = await res.json();20        setProducts(data.products);21      } catch (err) {22        if (err.name !== "AbortError") setError(err.message);23      } finally {24        if (!controller.signal.aborted) setLoading(false);25      }26    }27 28    load();29    return () => controller.abort();30  }, [category]);31 32  if (loading) return <p>Loading...</p>;33  if (error) return <p>{error}</p>;34  return products.map((p) => <div key={p._id}>{p.name}</div>);35}

1/5The effect creates an AbortController for this run.

Fetch products whenever the category changes, and cancel stale requests.

Save yourself the pain

Common mistakes

Oops

Writing useEffect(async () => { ... }).

Do this instead

An async function returns a promise, but React expects nothing or a cleanup function. Put the async function inside the effect.

Oops

Leaving out the dependency array and calling setState inside the effect.

Do this instead

That causes an infinite loop: render, effect, setState, render... Always pass the array and list what the effect uses.

Oops

Using an effect to copy props into state, like setFullName(first + " " + last).

Do this instead

Compute it during render: const fullName = first + " " + last. Fewer effects, fewer bugs.

Your mission

Three small effects

~30 min

Quick check

When does an effect with the dependency array [userId] run?

Go deeper

  1. 1Fetch products from an API inside useEffect and store them in state.
  2. 2Learn how the dependency array controls when the effect runs again.
  3. 3Return a cleanup function to clear timers and cancel requests.

More topics at this stop

Stuck on this topic? Ask an Insider

Get 1:1 guidance from people who've walked this exact path — on the InsideEdge app.

Download
InsideEdge