Popular Searches
Popular Course Categories
Popular Courses

useEffect Hook

useEffect Hook

React Hooks Fundamentals

useEffect Hook in React JS – Complete Detailed Notes

The useEffect Hook is a built-in React Hook used to synchronize a functional component with external systems, such as APIs, timers, browser events, subscriptions, and third-party libraries. It allows developers to perform side effects after React has updated the screen.

To learn more about React JS, visit JustAcademy React JS Training or Register for React JS Course Demo.


1. What Is the useEffect Hook?

In React, components primarily calculate and return the UI based on their props and state. However, applications often need to interact with systems outside React. These operations are called side effects.

The useEffect Hook allows you to run setup code after a component commits an update to the screen. It can also return a cleanup function that stops or reverses the setup when necessary.

Examples of side effects

  • Fetching data from an API.
  • Starting and clearing a timer.
  • Adding and removing browser event listeners.
  • Connecting to a chat server or WebSocket.
  • Subscribing to an external data source.
  • Synchronizing a third-party widget with React state.

Basic syntax

import { useEffect } from 'react';

useEffect(() => {
  // Side-effect or synchronization logic

  return () => {
    // Optional cleanup logic
  };
}, [dependencies]);

Important: The cleanup function is optional. The dependency array is also optional, but the way the Effect runs depends on whether you provide it.


2. Why Do We Use useEffect?

The useEffect Hook is useful when a React component needs to keep something outside React synchronized with its current props or state.

Requirement How useEffect Helps
Fetch API data Loads external information and stores the result in state.
Run a timer Starts a timer and clears it when no longer required.
Listen to window events Adds an event listener and removes it during cleanup.
Synchronize a widget Updates a third-party widget when relevant state changes.
Connect to a service Creates a connection and disconnects when dependencies change or the component is removed.

Not every operation requires useEffect. For example, calculating a total from existing state or handling a button click can usually be done directly during rendering or inside the event handler.


3. Understanding the Parameters of useEffect

The useEffect Hook has two parameters: a setup function and an optional dependency array.

3.1 Setup function

The setup function contains the logic that should run after the component commits to the screen. It may return a cleanup function.

useEffect(() => {
  console.log('Effect executed');
}, []);

3.2 Dependency array

The dependency array tells React which reactive values the Effect uses. React compares each dependency with its previous value using Object.is. When a dependency changes, React runs the previous cleanup, if provided, and then executes the new setup.

useEffect(() => {
  console.log('Count changed');
}, [count]);

In this example, the Effect runs after the initial commit and again when count changes.


4. Different Ways to Use useEffect

4.1 useEffect Without a Dependency Array

When the dependency array is omitted, the Effect runs after every committed render.

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    console.log('Component rendered');
  });

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

export default Counter;

Explanation: The Effect runs after the initial commit and after each subsequent commit. Clicking the button changes the state and causes another render, so the Effect runs again.

4.2 useEffect With an Empty Dependency Array

An empty dependency array means the Effect has no reactive dependencies. React runs its setup after the initial commit, with cleanup when the component is removed. In development Strict Mode, React may perform an additional setup-and-cleanup cycle to help detect bugs.

import { useEffect } from 'react';

function Welcome() {
  useEffect(() => {
    console.log('Welcome component mounted');

    return () => {
      console.log('Welcome component cleanup');
    };
  }, []);

  return <h2>Welcome to React JS</h2>;
}

export default Welcome;

Explanation: The Effect is intended to initialize something when the component appears. Its cleanup runs when the component is removed. Do not assume the setup executes exactly once in every development environment.

4.3 useEffect With Dependencies

Use a dependency array when the Effect must respond to changes in specific props or state values.

import { useEffect, useState } from 'react';

function UserStatus() {
  const [status, setStatus] = useState('Offline');

  useEffect(() => {
    console.log('Current status:', status);
  }, [status]);

  return (
    <div>
      <p>Status: {status}</p>
      <button onClick={() => setStatus('Online')}>
        Go Online
      </button>
    </div>
  );
}

export default UserStatus;

Explanation: The Effect runs after the initial commit and whenever status changes. Clicking the button updates the status and causes the Effect to run again after the resulting commit.


5. Difference Between Dependency Array Options

Syntax When Setup Runs Typical Use
useEffect(fn) After every commit. Rare cases where synchronization must happen after every commit.
useEffect(fn, []) After the initial commit; cleanup on removal. Effects without reactive dependencies.
useEffect(fn, [value]) After the initial commit and when value changes. Synchronizing with a changing value.
useEffect(fn, [a, b]) After the initial commit and when a or b changes. Effects depending on multiple reactive values.

In all cases, the setup may run more than once. In development Strict Mode, React intentionally performs an extra setup-and-cleanup cycle to test the correctness of the Effect.


6. Complete Example: Counter With useEffect

This example demonstrates how useEffect reacts to a change in state.

import { useEffect, useState } from 'react';

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

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

  return (
    <div>
      <h2>Counter Application</h2>
      <p>Current Count: {count}</p>
      <button onClick={() => setCount(count + 1)}>
        Increase
      </button>
      <button onClick={() => setCount(0)}>
        Reset
      </button>
    </div>
  );
}

export default Counter;

How it works

  1. The component initializes count to zero.
  2. React renders the counter interface.
  3. The Effect updates the browser tab title with the current count.
  4. When the user clicks Increase, count changes.
  5. React renders the updated interface and runs the Effect because count changed.
  6. The browser tab title displays the new count.

This is an example of synchronizing React state with an external browser API.


7. Using useEffect to Fetch API Data

React applications commonly need to display information received from an API. A useEffect can start a request, while useState stores the loading status, result, and any error.

Example: Fetch Users

import { useEffect, useState } from 'react';

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

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

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

        if (!response.ok) {
          throw new Error('Failed to fetch users');
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== 'AbortError') {
          setError(err.message || 'Something went wrong');
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchUsers();

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

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

  return (
    <div>
      <h2>Users List</h2>
      <ul>
        {users.map(user => (
          <li key={user.id}>
            {user.name} - {user.email}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default Users;

Explanation

  • useState stores users, loading state, and errors.
  • useEffect starts the API request after the initial commit.
  • fetch() requests the user data.
  • response.ok checks whether the HTTP response was successful.
  • response.json() converts the response body into JavaScript data.
  • AbortController cancels the request during cleanup if it is still in progress.
  • map() displays each user in the interface.

Note: For larger applications, framework-provided data loading or a dedicated data-fetching library may offer caching, request deduplication, and better loading management.


8. Using useEffect With setInterval

The useEffect Hook can start a timer that updates the component at regular intervals. The cleanup function must clear the interval to prevent unwanted background work.

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    const intervalId = setInterval(() => {
      setSeconds(previousSeconds => previousSeconds + 1);
    }, 1000);

    return () => {
      clearInterval(intervalId);
    };
  }, []);

  return (
    <div>
      <h2>Timer</h2>
      <p>Elapsed Time: {seconds} seconds</p>
    </div>
  );
}

export default Timer;

Important concepts

  • setInterval() runs a callback repeatedly at the specified interval.
  • clearInterval() stops the interval.
  • setSeconds(previousSeconds => previousSeconds + 1) uses a functional state update to calculate the next value from the latest state.
  • The cleanup function clears the timer when the component is removed.

9. Cleanup Function in useEffect

A cleanup function releases resources or reverses the setup performed by an Effect. It is especially important for timers, event listeners, subscriptions, and network requests.

Example: Browser Event Listener

import { useEffect, useState } from 'react';

function WindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

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

    window.addEventListener('resize', updateWidth);

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

  return <h2>Window Width: {width}px</h2>;
}

export default WindowWidth;

How cleanup works:

  1. The component renders and the Effect adds the resize listener.
  2. When the browser window changes size, the listener updates the width state.
  3. When the component is removed, the cleanup function removes the listener.

This example assumes it runs in a browser. If the component is rendered on a server, access to window must be guarded or deferred to client-side code.

When does cleanup run?

  • Before React runs the Effect again because a dependency changed.
  • When the component is removed from the page.
  • During the additional development-only Strict Mode setup-and-cleanup cycle.

10. Rules of the useEffect Hook

  • Call useEffect at the top level of a function component or custom Hook.
  • Do not call useEffect inside loops, conditions, or nested functions.
  • Include all reactive values used by the Effect in the dependency array.
  • Keep the number and order of dependencies constant.
  • Return a cleanup function when the setup creates resources that need to be stopped or released.
  • Do not make the Effect callback itself async. Define an async function inside the Effect and call it instead.
  • Do not suppress dependency warnings just to prevent an Effect from running.
  • Use Effects for synchronization with external systems rather than for every state calculation.

Incorrect example: async Effect callback

// Incorrect
useEffect(async () => {
  const response = await fetch('/api/data');
  const data = await response.json();
}, []);

The callback returns a Promise rather than either nothing or a cleanup function. Define and invoke an async function inside the Effect instead.

Correct example

useEffect(() => {
  async function loadData() {
    const response = await fetch('/api/data');
    const data = await response.json();
    console.log(data);
  }

  loadData();
}, []);

In production code, also handle failed requests and consider how to cancel or ignore outdated requests.


11. Common Mistakes When Using useEffect

Mistake Why It Is a Problem Better Approach
Missing dependencies The Effect can use outdated props or state. Include all required reactive dependencies.
Forgetting cleanup Timers, listeners, or subscriptions may remain active. Return a cleanup function when necessary.
Updating state on every run without a condition May create an infinite render loop. Review dependencies and whether the Effect is needed.
Using an Effect for simple calculations Creates unnecessary state updates and complexity. Calculate derived values during rendering.
Making the Effect callback async The callback returns a Promise instead of a cleanup function. Declare an async function inside the Effect.
Assuming setup runs exactly once in development Strict Mode may intentionally run setup and cleanup an extra time. Write setup and cleanup so they work correctly when repeated.
Using a freshly created object as a dependency Its reference may change on every render, causing repeated execution. Move object creation inside the Effect or simplify the dependencies.

12. Understanding an Infinite Loop in useEffect

An infinite loop can occur when an Effect updates state and that update changes one of the Effect's dependencies, causing the Effect to run again.

Incorrect example

import { useEffect, useState } from 'react';

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

  useEffect(() => {
    setCount(count + 1);
  }, [count]);

  return <p>Count: {count}</p>;
}

Problem: The Effect changes count every time it runs. Because count is a dependency, each update causes the Effect to run again.

Better approach

If the goal is simply to initialize a counter, initialize it in useState. If the goal is to increase the counter after a user action, update it in an event handler.

import { useState } from 'react';

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

  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={() => setCount(value => value + 1)}>
        Increase
      </button>
    </div>
  );
}

13. useEffect vs Event Handlers

Use an event handler when code should run because a user performed a specific action. Use an Effect when a component needs to synchronize with an external system based on its current state or props.

useEffect Event Handler
Runs based on rendering and dependency changes. Runs in response to a specific event.
Useful for subscriptions, timers, and synchronization. Useful for submitting forms and handling button clicks.
May require cleanup. Usually does not require Effect cleanup.
Example: connect to a chat room when roomId changes. Example: send a message when the user clicks Send.

14. useEffect vs useLayoutEffect

Both Hooks let a component synchronize with external systems, but their timing differs.

Feature useEffect useLayoutEffect
Timing Generally runs after the browser has had a chance to paint for non-interaction updates. Runs after DOM changes but before the browser repaints.
Typical use Data synchronization, subscriptions, timers, and external connections. Measuring layout or positioning elements before they appear.
Performance Preferred for most Effects. Can block painting, so use only when necessary.

15. Practical Project: Digital Clock Using useEffect

Build a simple digital clock that displays the current time and updates every second.

import { useEffect, useState } from 'react';

function DigitalClock() {
  const [time, setTime] = useState(new Date());

  useEffect(() => {
    const timerId = setInterval(() => {
      setTime(new Date());
    }, 1000);

    return () => {
      clearInterval(timerId);
    };
  }, []);

  return (
    <div>
      <h1>Digital Clock</h1>
      <h2>{time.toLocaleTimeString()}</h2>
    </div>
  );
}

export default DigitalClock;

Project features

  • Displays the current local time.
  • Updates automatically every second.
  • Uses useState to store the current time.
  • Uses useEffect to start the timer.
  • Uses cleanup to stop the timer when the component is removed.

Additional practice tasks

  1. Add a Start and Stop button to control the clock.
  2. Create a countdown timer.
  3. Display the current date along with the time.
  4. Fetch weather information from an API when a city changes.
  5. Subscribe to a browser event and clean it up properly.

16. Interview Questions and Answers

Q1. What is useEffect in React?

Answer: useEffect is a React Hook that synchronizes a component with external systems. It can run setup logic after a commit and optionally return a cleanup function.

Q2. What is the syntax of useEffect?

Answer: useEffect(() => { /* setup */ }, [dependencies]);. The setup function is required, while the dependency array is optional.

Q3. What happens if the dependency array is omitted?

Answer: The Effect runs after every committed render.

Q4. What happens if the dependency array is empty?

Answer: The Effect setup runs after the initial commit and its cleanup runs when the component is removed. Development Strict Mode may run an extra setup-and-cleanup cycle.

Q5. What is a cleanup function?

Answer: It is a function returned by an Effect to stop or undo setup work, such as clearing timers, removing event listeners, or disconnecting from a service.

Q6. Can useEffect be used to fetch API data?

Answer: Yes. An Effect can start an API request and update state with the result. The code should handle loading, errors, and outdated or cancelled requests appropriately.

Q7. Why should we include dependencies?

Answer: Dependencies keep the Effect synchronized with the current reactive values it uses, helping prevent stale values and unexpected behavior.

Q8. Can we call useEffect inside an if statement?

Answer: No. Hooks must be called at the top level of a function component or custom Hook. Conditional logic can be placed inside the Effect when appropriate.

Q9. Why can an infinite loop happen in useEffect?

Answer: It can happen when the Effect updates state and that update changes a dependency, causing the Effect to run repeatedly.

Q10. Can the useEffect callback be async?

Answer: The callback itself should not be async because it must return either nothing or a cleanup function. Define an async function inside the Effect and call it instead.

Q11. What is the difference between useEffect and useLayoutEffect?

Answer: useEffect is suitable for most synchronization tasks. useLayoutEffect runs before the browser repaints and is useful when layout measurements or visual positioning must happen before painting.

Q12. Should every state update be handled using useEffect?

Answer: No. User-triggered actions belong in event handlers, and values derived from existing state can usually be calculated during rendering. Use Effects when synchronization with an external system is needed.


17. Practice Exercises

  1. Create a component that changes the browser tab title whenever a username changes.
  2. Build a stopwatch with Start, Stop, and Reset buttons using useEffect.
  3. Fetch a list of products from an API and display loading and error messages.
  4. Track the browser window width using a resize event listener.
  5. Create a component that connects to a simulated service and disconnects during cleanup.
  6. Find and fix an infinite loop caused by incorrect Effect dependencies.
  7. Explain why development Strict Mode may run an additional setup-and-cleanup cycle.

18. Quick Revision Checklist

  • Understand the purpose and syntax of useEffect.
  • Know the difference between no dependency array, an empty array, and a dependency array with values.
  • Include all reactive dependencies used by the Effect.
  • Understand setup and cleanup behavior.
  • Know how to fetch API data and handle errors or cancelled requests.
  • Know how to manage timers and browser event listeners.
  • Avoid unnecessary Effects and infinite state-update loops.
  • Understand the development-only Strict Mode setup-and-cleanup cycle.
  • Know when useEffect differs from event handlers and useLayoutEffect.

19. Official React Documentation


20. Conclusion

The useEffect Hook is an important part of React JS for synchronizing components with external systems. By understanding setup functions, dependency arrays, cleanup logic, API requests, timers, and event listeners, developers can build applications that behave reliably and avoid common bugs.

Practice these examples and exercises to strengthen your understanding of React Hooks. Explore JustAcademy React JS Training and Register for React JS Course Demo for additional learning opportunities.

Previous Next
whatsapp