DEV Community

_sondos Ch
_sondos Ch

Posted on Edited on

useEffect Hook in React : Understand useEffect in a single article for beginners

definition :

is a react hook (function provided by react) that lets you synchronize with an external system (like : fetch data from server or local storage , server connection , …)

syntax :

useEffect(callback function , dependency list) : void

callback: Holds your side-effect logic. Unlike the component render body (which must remain pure), this function interacts with external systems, browser APIs, or outside state, so it is impure by nature.

Execution timing:Runs after the component renders and updates the screen. While it usually executes after the browser paints, updates triggered by direct user interactions (such as a click) may run before painting ,if you need code to run strictly before the browser paints, use useLayoutEffect . Synchronous code inside the effect runs immediately, whereas asynchronous operations (such as network requests) are handed off to the browser and handled via the JavaScript event loop see Event Loop details here.

Cleanup function (optional): Can return () => { ... } (otherwise implicitly returns undefined). It does not run on initial mount; instead, React invokes it right before re-running the effect (using the previous render's values to tear down old resources first, such as closing a previous connection before opening a new one) or when the component unmounts.

dependencyList: Must be a fixed-length array across renders containing props, state, or reactive values declared inside the component body.
It behaves in three ways:

  • Omitted (no array passed — default)
    : Runs after initial mount and after every render.

  • Empty array ([])
    : Runs only once on mount, since an empty dependency list never changes across renders.

  • Populated array ([a, b, ...]):
    React stores initial values (version 1) and, on subsequent renders, compares current values (version 2) against previous ones using Object.is(prevValue, nextValue) (by value for primitives. by reference for objects, arrays, and functions). If Object.is returns true, the effect is skipped. if false, it runs again (and updating state triggers a UI re-render).
    (see comparison details here).

Examples:

Basic Fetch on Mount

// Always call useEffect at the top level (means the top level of the component function body, not the parent component. Each component (parent or child) can have its own useEffect, as long as it is not called inside conditions, loops, or nested functions.)
import { useState, useEffect } from 'react';

export function UserProfile() {
  const [data, setData] = useState(null);

  useEffect(() => {
    async function getData() {
      const result = await fetchData();
      setData(result);
    }

    getData();
  }, []); // Runs once on mount because [] never changes across renders

  if (!data) return <p>Loading...</p>;

  return (
    <div>
      <img src={data.img} alt={data.title} />
      <h4>{data.title}</h4>
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

** Cleanup on Dependency Change or Unmount**

import { useEffect } from 'react';

export function ChatRoom({ roomId }) {
  useEffect(() => {
    const connection = createConnection(roomId);
    connection.connect();

    // Runs before re-connecting to a new roomId, or when ChatRoom unmounts
    return () => {
      connection.disconnect();
    };
  }, [roomId]);

  return <h4>Connected to {roomId}</h4>;
}


Enter fullscreen mode Exit fullscreen mode

StrictMode note: In development only, with (the default in Vite and Next.js), React intentionally runs the effect twice: run → cleanup → run. The goal is to make sure your cleanup function works correctly. That's why you may see console.log messages twice during development. This is normal and does not happen in production.

Summary in pictures :

Top comments (0)