Typorithm · medium

useEffect

react-useeffectreactuseeffecteffectcleanup
Saved on this device
Full lesson · 8 learning steps Open any exercise for focused practice
1

Step 1 of 8 · intro card

Learn useEffect

0%

Hooks

useEffect(callback, deps) runs side effects after render. The function it returns is cleanup, run before the next effect and on unmount. The dependency array controls re-runs: [] means once on mount. Forgetting cleanup leaks timers and subscriptions.

useEffect lets you run side effects — things outside React's render, like timers, subscriptions, or fetches. The callback runs after the component has rendered to the screen, so it never blocks painting.

If the callback returns a function, that is the cleanup. React runs it before re-running the effect and once more when the component unmounts. Here clearInterval(id) tears down the timer so it does not keep firing.

The dependency array decides when the effect re-runs: it re-runs whenever a listed value changes. An empty array [] means run once on mount and never again. Forgetting the cleanup is the classic bug — leaked intervals and subscriptions that fire on unmounted components.

01

useEffect runs side effects after render.

02

The returned function is cleanup (next effect + unmount).

03

[] runs the effect once on mount.

import { useEffect, useState } from "react";

function Timer() {
  const [now, setNow] = useState(Date.now());
  useEffect(() => {
    const id = setInterval(() => setNow(Date.now()), 1000);
    return () => clearInterval(id);
  }, []);
  return <span>{now}</span>;
}

Read the implementation

Connect each part of the code to the concept before you type.

1. Run an effect

useEffect runs its callback after the component renders to the screen.

useEffect(() => {

2. The side effect

Starting an interval is a side effect, so it belongs inside useEffect, not in render.

const id = setInterval(() => setNow(Date.now()), 1000);

3. Cleanup function

The returned function is cleanup; React runs it before the next effect and on unmount.

return () => clearInterval(id);

4. Dependency array

An empty dependency array means the effect runs once on mount and never re-runs.

}, []);

5. Stop the timer

Clearing the interval prevents a leaked timer from firing after the component is gone.

clearInterval(id)

A complete learning loop

01

Understand

Read the concept map and follow the code breakdown.

02

Reconstruct

Type the implementation, repair mistakes and work through every recall exercise.

03

Verify

Use the final check without hints; revisit weak concepts in short practice sessions.

useEffect: Lesson & Practice · Typorithm | ApplyDjinn