useEffect

what is useEffect() ?

  • Profile picture of Mcs
  • by Mcs July 2, 2025

useEffect is a React Hook that allows functional components to perform side effects, such as data fetching, subscriptions, or manually updating the DOM. It's similar to componentDidMount, componentDidUpdate, and componentWillUnmount in class components. It lets you synchronize a component with an external system.

What is a Side Effect?

A side effect is anything that happens outside the component rendering, like:

  1. Fetching data from an API
  2. Updating the DOM directly
  3. Starting a timer
  4. Subscribing/unsubscribing to events

Basic Syntax

useEffect(() => {
 // code to run after render (side effect)
}, [dependencies]);

  1. The function inside runs after the component renders.
  2. The [dependencies] array controls when it runs.

Example: Run on Every Render

This runs every time the component renders.

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

Example: Run Only Once (on mount)

The empty array [] means run only once (like componentDidMount in class components).
 

useEffect(() => {
 console.log('Component mounted');
}, []);

Example: Re-run When Value Changes

Runs only when the count value changes.

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

Example: Clean Up (like unmount)

useEffect(() => {
 const timer = setInterval(() => {
   console.log('tick');
 }, 1000);

 return () => {
   clearInterval(timer); // clean up on unmount
 };
}, []);

Real-Life Example: Fetch Data

import { useEffect, useState } from 'react';

function Users() {
 const [users, setUsers] = useState([]);

 useEffect(() => {
   fetch('https://jsonplaceholder.typicode.com/users')
     .then(res => res.json())
     .then(data => setUsers(data));
 }, []);

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

Summary

FeatureDescription
useEffect()Handles side effects in function components
Empty []Runs once on mount
[dependency]Runs when value in array changes
Return a functionFor cleanup (likecomponentWillUnmount)