Lesson 10 / 1191%

Lesson 10

Effects with useEffect

25 min

Fetch data from an API, handle loading and clean up effects.

Definition

useEffectis a React hook that allows you to synchronize a component with an external system, generally after it has been rendered. It is used to manage side effects, such as calling an API, starting a timer, listening for an event, or changing the page title. It receives a function containing the effect and, optionally, a dependency array indicating when the effect should run again.

So far, you have learned how to display data, use props, and manage interactions with React. However, some features require communication with elements outside the component: the browser, a server, or a JavaScript timer. This is where useEffect becomes useful.

In this lesson, you will understand how this hook works, learn to manage its dependencies, fetch data from an API, and properly clean up effects. You will also discover situations where it is better not to useuseEffect.

What Is a Side Effect?

A React component should primarily calculate what it displays based on its props and state. However, it sometimes needs to perform an action beyond this simple calculation: fetching data from a server, changing the browser tab title, or starting a stopwatch. These operations are called side effects.

In programming, a side effect is an action that changes something outside the direct result of a function. For example, a function that calculates a sum normally produces no external effect. On the other hand, a function that sends a network request interacts with another system.

React aims to keep component renderingpredictable. With the same props and state, a component should produce the same result. If you trigger a request directly inside a component's body, it may repeat on every render.useEffect separates these operations from the rendering logic.

Some Examples of Side Effects

  • Calling an API:fetching a list of articles, products, or users from a server.
  • Modifying the document:changing the browser tab title or synchronizing a class on the body element.
  • Starting a timer:creating a stopwatch, countdown, or automatic refresh.
  • Listening for an event:detecting window resizing, keyboard input, or page scrolling.
  • Saving data:synchronizing a value with the browser's local storage.
  • Connecting to a service:establishing a connection to an external system, then closing it when the component disappears.

Note that actions directly triggered by the user, such as clicking a button or submitting a form, generally do not require useEffect. They should be handled in event handlers such as onClick or onSubmit.

The useEffect Syntax

basic structure
import { useEffect } from "react";

function Example() {
  useEffect(() => {
    // Code executed after rendering
  }, []);

  return <p>Hello React!</p>;
}

export default Example;

The function passed to useEffectcontains the effect's code. The second argument is adependency array. It tells React which values to monitor to determine whether the effect should run again.

  • Empty array []:the effect runs after the component's initial mount, without running again for ordinary updates to its props or state.
  • Array [value]:the effect runs on mount and then whenever that value changes.
  • No array:the effect runs after every committed render of the component.

Dependencies are compared with their previous values. If a dependency changes, React first performs any cleanup from the previous effect, then runs the new effect. This behavior keeps the component synchronized with its current values.

The Three Forms of useEffect Side by Side

To visualize the differences, here are three effects that display messages in the console. Observe what happens during the initial render and after each button click.

three dependency arrays
import { useEffect, useState } from "react";

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

  // On mount
  useEffect(() => {
    console.log("Initial render");
  }, []);

  // On mount and whenever count changes
  useEffect(() => {
    console.log("Count:", count);
  }, [count]);

  // After every render
  useEffect(() => {
    console.log("A render just occurred");
  });

  return (
    <button onClick={() => setCount(c => c + 1)}>
      Clicks: {count}
    </button>
  );
}

export default Demo;

During the initial mount, all three effects run. After each click, the count changes: the second and third effects run again. The first effect does not run again during these updates because its dependency array is empty. In development, StrictModemay cause additional executions to verify that effects are properly cleaned up.

First Example: The Browser Tab Title

Let's start with a simple effect. Whenever the counter changes, we will update the browser tab title using document.title. Since the effect uses the count value, it must appear in the dependency array.

updating document.title
import { useEffect, useState } from "react";

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

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

  return (
    <button onClick={() => setCount(c => c + 1)}>
      Clicked {count} times
    </button>
  );
}

export default TitleCounter;
Browser screenshot showing a tab titled Clicks: 3 and a button labeled Clicked 3 times.

When you click the button, React updates the counter and renders the component again. After this update, the effect changes the browser tab title. The browser therefore displays the same number of clicks as the button. This is an example of synchronization between React state and an external element.

The Dependency Rule

Reactive values used inside the effect, including props, state variables, and variables declared inside the component, must appear in the dependency array. Otherwise, the effect may use outdated values. Tools such as ESLint can detect missing dependencies. Stable values outside the component, such as certain global objects, do not need to be included.

Fetching Data from an API

A common use of useEffectis fetching data from a server. For example, an application may load a list of users when it opens. To do this, we generally use the JavaScript fetch() function.

You should handle three situations:loading, while the request is in progress; success, when the data becomes available; and error, when the request fails. Handling these states provides clear feedback to the user.

src/components/Users.jsx
import { useEffect, useState } from "react";

function Users() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    async function load() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Network error");
        }

        const data = await response.json();
        setUsers(data);
      } catch (e) {
        if (e.name !== "AbortError") {
          setError(e.message);
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    load();

    return () => controller.abort();
  }, []);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <ul>
      {users.map((user) => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

export default Users;

Initially, the component displays "Loading...". The effect then starts the request. If the server responds successfully, the data is stored in the users state, which triggers another render. If an error occurs, the corresponding message is displayed.

The AbortController allows the request to be canceled when the component unmounts. This prevents certain unnecessary asynchronous operations from continuing. It is especially useful when requests may take a long time.

Two screenshots showing the Loading message followed by the user list after the data has been received.

Why Not Make the Effect Async?

The function passed directly touseEffect should not be declared async. An asynchronous function returns a Promise, whereas React expects an optional cleanup function. The correct approach is to declare an asynchronous function inside the effect and then call it.

Running a Request Again When a Value Changes

Some data depends on the user's selection. For example, when the user selects another article, the component must load the corresponding information. The dependency array allows this new request to be triggered automatically.

loading an article by its ID
import { useEffect, useState } from "react";

function Article() {
  const [id, setId] = useState(1);
  const [article, setArticle] = useState(null);

  useEffect(() => {
    const controller = new AbortController();

    setArticle(null);

    async function load() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/posts/" + id,
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Article not found");
        }

        const data = await response.json();
        setArticle(data);
      } catch (e) {
        if (e.name !== "AbortError") {
          console.error(e);
        }
      }
    }

    load();

    return () => controller.abort();
  }, [id]);

  return (
    <div>
      <button onClick={() => setId(i => i + 1)}>
        Next article
      </button>

      {article ? (
        <h2>{article.title}</h2>
      ) : (
        <p>Loading article...</p>
      )}
    </div>
  );
}

export default Article;

With each click, the identifier changes. React detects this change, cleans up the previous effect, and starts a new request. The controller also cancels the previous request, helping to prevent problems when the user clicks quickly.

Cleaning Up an Effect

Some effects start operations that continue running: a timer, a connection, or an event listener. These operations must be stopped when the component unmounts or the effect needs to be recreated. To do this, useEffectcan return a cleanup function.

a stopwatch with cleanup
import { useEffect, useState } from "react";

function Stopwatch() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => {
      setSeconds((s) => s + 1);
    }, 1000);

    return () => clearInterval(timer);
  }, []);

  return <p>Elapsed time: {seconds} s</p>;
}

export default Stopwatch;

The timer increases the number of seconds every 1,000 milliseconds. The clearInterval() function stops the timer when the effect is cleaned up. Without this cleanup, unnecessary timers could continue running, especially during subsequent mounts.

When Does Cleanup Run?

  • On unmount:when the component is removed from the interface.
  • Before running again:when dependencies change, React cleans up the previous effect.
  • In development:React may perform an additional setup and cleanup cycle with StrictMode.

Listening for Window Size Changes

The same principle applies to browser events. For example, you can monitor the window width to update information on the screen. You must add the event listener when the effect starts and remove it during cleanup.

event listener with cleanup
import { useEffect, useState } from "react";

function WindowWidth() {
  const [width, setWidth] = useState(0);

  useEffect(() => {
    function updateWidth() {
      setWidth(window.innerWidth);
    }

    updateWidth();

    window.addEventListener("resize", updateWidth);

    return () => {
      window.removeEventListener("resize", updateWidth);
    };
  }, []);

  return <p>Window width: {width} px</p>;
}

export default WindowWidth;

Whenever the window is resized, the browser triggers the resize event. The updateWidth function then retrieves the new width. When the component unmounts,removeEventListener()removes the listener. Initializing the value to zero also avoids accessing window during possible server-side rendering.

Saving a Value in localStorage

The browser's local storage, called localStorage, allows certain data to be preserved after the page is reloaded. You can use useEffectto save a value whenever it changes.

saving a counter
import { useEffect, useState } from "react";

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

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

  return (
    <button onClick={() => setCount(c => c + 1)}>
      Count: {count}
    </button>
  );
}

export default SavedCounter;

This example saves the counter whenever it changes. However, it does not yet restore the value when the page loads: the counter is initialized to zero. To truly preserve the counter between visits, you must also read the stored value during initialization. You will encounter this logic again in projects that use local storage.

Understanding StrictMode

In development, React may perform an additional setup and cleanup cycle for effects when using StrictMode. This helps detect cleanup and synchronization problems. You may therefore observe two network requests during development. This verification behavior does not apply in the same way in the production version.

When Not to Use useEffect

It can be tempting to use useEffectwhenever data changes. However, this hook is not necessary for calculations that can be performed directly during rendering. An unnecessary effect can complicate the component and cause extra renders.

avoid: using an effect for a simple calculation
import { useEffect, useState } from "react";

// Avoid
function Profile({ firstName, lastName }) {
  const [fullName, setFullName] = useState("");

  useEffect(() => {
    setFullName(firstName + " " + lastName);
  }, [firstName, lastName]);

  return <h2>{fullName}</h2>;
}
preferred: calculate directly
// Preferred
function Profile({ firstName, lastName }) {
  const fullName = firstName + " " + lastName;

  return <h2>{fullName}</h2>;
}

The second version is simpler. The full name is calculated immediately from the props, without additional state. It avoids an intermediate render with an outdated value. Remember this rule:if a value can be calculated during rendering, you generally do not need an effect.

Do Not Use an Effect for a Click

handle an action directly
function MessageButton() {
  function showMessage() {
    alert("Hello!");
  }

  return (
    <button onClick={showMessage}>
      Show a message
    </button>
  );
}

In this example, the action depends directly on the user's click. It should therefore be executed in the onClick handler, not inside an effect. This distinction makes components easier to understand.

Avoiding Infinite Loops

A common mistake is updating state inside an effect that runs after every render. If this update triggers another render every time, the component may enter an infinite loop.

example of an infinite loop to avoid
import { useEffect, useState } from "react";

function BadCounter() {
  const [number, setNumber] = useState(0);

  // Avoid: infinite update loop
  useEffect(() => {
    setNumber(n => n + 1);
  });

  return <p>{number}</p>;
}

Here, the effect increases the number after every render. This change triggers another render, which runs the effect again, and so on. To avoid this problem, you must identify the actual reason why the state should change. For example, a counter controlled by a button should be updated directly in onClick.

Common Mistakes

  • Forgetting dependencies:the effect may run too often or use outdated values.
  • Using objects recreated on every render:their references change and may trigger unnecessary effects.
  • Forgetting cleanup:timers and event listeners may continue running unnecessarily.
  • Declaring an effect directly as async:the asynchronous function should be placed inside the effect.
  • Ignoring network errors:users may see an empty or unresponsive interface.
  • Creating an effect for a calculation:a simple JavaScript expression is often enough.
  • Triggering an infinite loop:updating state after every effect can cause endless renders.

Best Practices

  • Use useEffectprimarily to synchronize your component with an external system.
  • Declare hooks at the top level of the component, never inside a loop or condition.
  • Include all necessary reactive dependencies in the dependency array.
  • Clean up timers, connections, and event listeners.
  • Handle loading, error, and success states when making network requests.
  • Avoid additional state when values can be calculated directly.

Key Takeaways

  • useEffect managesside effectsand synchronizes a component with external systems.
  • The dependency arraydetermines when an effect should run again.
  • An empty array []prevents the effect from running again during ordinary component updates.
  • API calls should handleloading,errors, and request cancellation when necessary.
  • A cleanup functionstops operations started by an effect.
  • StrictModemay cause additional effect executions during development.
  • Simple calculations and actions directly triggered by the user generally do not requireuseEffect.

Exercise

Create a component that fetches the list of posts from the APIhttps://jsonplaceholder.typicode.com/posts. Display only the first ten titles. Show a "Loading..." message while the request is in progress and an "Error" message if it fails. Use useEffectand useState, then verify that the list appears after loading.

Go Further

Add a "Reload" button that runs the request again by changing a value included in the effect's dependency array. Then add an AbortControllerto cancel the previous request when a new one starts. Finally, verify that loading and error messages remain correctly displayed.