Aral Code

Effects & Data Lesson 11 of 13

React useEffect — Timers, Titles and Fetching Data

Run side effects with useEffect — update the page title, start and clean up timers, sync with localStorage, and fetch data from an API with loading and error states.

A component's main job is to return JSX. Anything else, like starting a timer, changing the browser tab title, saving to storage or loading data from a server, is a side effect. React runs side effects with the useEffect hook.

Basic useEffect

Example Update the tab title
<div id="root"></div>
<script src="/vendor/react.min.js"></script>
<script src="/vendor/react-dom.min.js"></script>
<script src="/vendor/babel.min.js"></script>
<script type="text/babel">
  const { useState, useEffect } = React;

  function App() {
    const [count, setCount] = useState(0);

    useEffect(() => {
      document.title = `(${count}) Notifications`;
    }, [count]);

    return (
      <div style={{ fontFamily: "sans-serif", padding: 16 }}>
        <p>Notifications: {count}</p>
        <button onClick={() => setCount(count + 1)}>New message</button>
      </div>
    );
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>

useEffect(fn, deps) runs fn after React updates the page. The dependency array [count] says "run again whenever count changes".

The dependency array

CodeEffect runs…
useEffect(fn, [a, b])After the first render, and when a or b changes
useEffect(fn, [])Only once, after the first render
useEffect(fn)After every render (rarely what you want)

Timers and cleanup

If an effect starts something ongoing, return a cleanup function that stops it:

Example A clock with cleanup
<div id="root"></div>
<script src="/vendor/react.min.js"></script>
<script src="/vendor/react-dom.min.js"></script>
<script src="/vendor/babel.min.js"></script>
<script type="text/babel">
  const { useState, useEffect } = React;

  function Clock() {
    const [now, setNow] = useState(new Date());
    useEffect(() => {
      const id = setInterval(() => setNow(new Date()), 1000);
      return () => clearInterval(id);       // cleanup when the clock is removed
    }, []);
    return <h2 style={{ fontFamily: "monospace" }}>{now.toLocaleTimeString("en-PH")}</h2>;
  }

  function App() {
    const [show, setShow] = useState(true);
    return (
      <div style={{ padding: 16 }}>
        <button onClick={() => setShow(!show)}>{show ? "Hide" : "Show"} clock</button>
        {show && <Clock />}
      </div>
    );
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>

Without the cleanup, hiding the clock would leave the interval running in the background forever. Cleanups also apply to event listeners and subscriptions.

Fetching data

Loading data from a server is the most common effect. This example simulates a slow server with a promise, so it works offline:

Example Loading data with loading and error states
<div id="root"></div>
<script src="/vendor/react.min.js"></script>
<script src="/vendor/react-dom.min.js"></script>
<script src="/vendor/babel.min.js"></script>
<script type="text/babel">
  const { useState, useEffect } = React;

  // Pretend server: replace with fetch("/api/students") in a real app
  function fetchStudents(section) {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        if (section === "Luna") reject(new Error("Section not found"));
        else resolve([
          { id: 1, name: `Ana (${section})` },
          { id: 2, name: `Ben (${section})` },
        ]);
      }, 800);
    });
  }

  function StudentList({ section }) {
    const [students, setStudents] = useState([]);
    const [status, setStatus] = useState("loading");

    useEffect(() => {
      let ignore = false;
      setStatus("loading");
      fetchStudents(section)
        .then((data) => { if (!ignore) { setStudents(data); setStatus("done"); } })
        .catch(() => { if (!ignore) setStatus("error"); });
      return () => { ignore = true; };      // ignore old responses
    }, [section]);

    if (status === "loading") return <p>⏳ Loading {section}…</p>;
    if (status === "error") return <p style={{ color: "crimson" }}>Could not load {section}.</p>;
    return <ul>{students.map((s) => <li key={s.id}>{s.name}</li>)}</ul>;
  }

  function App() {
    const [section, setSection] = useState("Rizal");
    return (
      <div style={{ fontFamily: "sans-serif", padding: 12 }}>
        {["Rizal", "Mabini", "Luna"].map((s) => (
          <button key={s} onClick={() => setSection(s)} disabled={s === section} style={{ marginRight: 6 }}>{s}</button>
        ))}
        <StudentList section={section} />
      </div>
    );
  }
  ReactDOM.createRoot(document.getElementById("root")).render(<App />);
</script>

With a real server, you'd write fetch(url).then((r) => r.json()) instead of fetchStudents. The ignore flag prevents an old, slow response from overwriting a newer one when the user switches sections quickly.

Saving to localStorage

const [notes, setNotes] = useState(() => localStorage.getItem("notes") ?? "");

useEffect(() => {
  localStorage.setItem("notes", notes);
}, [notes]);

Passing a function to useState reads storage only once, on the first render. (The Try-it editor blocks localStorage, so test this in a real project.)

Quick Quiz

Check what you learned. Walang grade ito, practice lang. 🙂

1. When does useEffect(fn, []) run?
2. What is the cleanup function for?
3. What does [section] in useEffect mean?
4. Should you use useEffect to compute a filtered list?

By Sir Reyel · Last updated 2026-12-04