Skip to content
engineering workbench.by StudyPort Academy
Learning path
Intermediate22 minLESSON 04 / 8

Effects and side effects

01

Understand the idea

Rendering should describe the screen. Talking to the network, a timer, or a is a — and useEffect is where that work belongs.

Render first, then the effect

When a component function runs, it should calculate UI from props and . It should not, as a first habit, start a network request in the middle of that calculation.

A is work that reaches outside that calculation: fetch, setInterval, addEventListener, talking to a third-party widget. useEffect schedules that work after React has updated the screen.

You call useEffect with two arguments: a function that does the outside work (and may return a cleanup function), and an optional dependency array that decides when to run again.

The dependency array in plain words

The second argument is an array of values your effect uses.

  • No array at all: run after every render. Easy to create loops if you also set state.
  • Empty array: run after the first render (mount). Clean up when the component leaves the page.
  • Array with values, for example userId: run after mount, and again when userId changes.

List every state or prop value the effect reads. If you leave one out, the effect can “see” an old value - a stale closure.

Three common useEffect shapes
You writeWhen it runsGood for
useEffect with only the functionAfter every renderRare - dangerous if it sets state every time
useEffect with an empty dependency arrayOnce after mountOne subscription or one load
useEffect with id in the dependency arrayMount and when id changesReload when a route id changes

Fetching data and cleaning up

Put the fetch inside useEffect. When the component unmounts, or when the effect is about to re-run, return a cleanup function.

A common pattern is an ignore flag: set ignore = true in cleanup, and only call setState if ignore is still false when the response arrives. That way a slow response cannot overwrite a newer screen.

In development, Strict Mode may run setup, cleanup, and setup again. That is a check for missing cleanup. Production does not add that extra cycle.

Stale values inside an effect

The function you pass to useEffect closes over the props and state from the render that created it. An interval started with an empty dependency array will keep seeing the first count unless you put count in the dependency list (and clear the old interval in cleanup), or you update with a functional setter that receives the previous count so you do not need the old count from the closure.

How to read the live example

  1. App renders and shows the word loaded.
  2. After that paint, the effect runs because the dependency array is empty (mount only).
  3. The effect logs five labels: loaded, cleanup, deps, once, effect.
  4. The empty cleanup function is a placeholder for “put cleanup here when you have something to undo.”

When something on a team “fetches forever” or “shows old data,” read the dependency array before you rewrite the URL.

02

Mental model

FOLLOW THE VALUE

render
commit
effect

Effects run after paint.

01 / 03Trace the transformation

03

Live example

The example runs an effect once on mount (empty dependency ) and logs five labels that name the effect ideas for this lesson.

import { useEffect } from "react"; // Side effects after render.
export default function App() {
  useEffect(() => {
    console.log("loaded"); // Effect work ran.
    console.log("cleanup"); // Cleanup belongs with the effect.
    console.log("deps"); // Dependencies decide when this reruns.
    console.log("once"); // Empty array means mount once.
    console.log("effect"); // This is the effect itself.
    return () => {}; // Cleanup runs before the next effect or on unmount.
  }, []); // Empty dependency list.
  return <p>loaded</p>;
}

VISUAL FLOW

Try the same flow interactively

Open Free sandbox to run the live timer. This walkthrough is that same lifecycle: effect starts once, interval updates tick, cleanup stops the timer.

Step 1 of 8

Click through the timer lifecycle

What the user sees

…

Import the hooks you need

import { useEffect, useState } from "react";

useState remembers the counter. useEffect manages the timer after React paints the screen.

04

Guided challenge

Run the effect once

The effect logs every. Change that log to once, matching an effect that lists an empty dependency array instead of omitting it.

import { useEffect } from "react";
export default function App() {
  useEffect(() => {
    console.log("loaded"); // Keep this log.
    console.log("cleanup"); // Keep this log.
    console.log("deps"); // Keep this log.
    console.log("every"); // Wrong - change to once, and add [].
    console.log("effect"); // Keep this log.
  }); // Missing dependency array runs after every render.
  return <p>loop risk</p>;
}

EXPECTED CONSOLE OUTPUT

loaded
cleanup
deps
once
effect

Hints 0/2

    05

    Free sandbox

    Make a variation, test an assumption, or break the example on purpose. This draft is saved separately.

    import { useEffect, useState } from "react";
    export default function App() {
      const [tick, setTick] = useState(0); // Value the interval updates.
      useEffect(() => {
        const id = setInterval(() => setTick((value) => value + 1), 1000); // Start a timer.
        return () => clearInterval(id); // Clear it on cleanup.
      }, []); // Start once on mount.
      return <p>{tick}</p>;
    }
    
    
    06

    Quiz

    A quick check for understanding. Retry as often as you like; your learning path stays open.

    01What does useEffect do when you omit the dependency array?
    02Why return a function from an effect?

    Ready to call this one understood?

    Mark this lesson complete to earn 150 XP. You can always revisit it.

    Sign in to save progress
    Next lesson