Back to Roadmap
8:00

useEffect Hook

Learn how to handle side effects in React functional components using the useEffect Hook

8 MIN READ VERIFIED CURRICULUM

The useEffect Hook is used in React functional components to handle side effects such as data fetching, subscriptions, timers, and manual DOM updates.

It replaces lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount used in class components.

What is useEffect?

useEffect is a React Hook that lets you perform side effects in functional components.

Side effects are operations that interact with the outside world or affect something outside the component rendering.

import { useEffect } from 'react';

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

Basic Syntax of useEffect

useEffect takes two arguments: a callback function and an optional dependency array.

The dependency array controls when the effect runs.

useEffect(() => {
  // side effect logic
}, [dependencies]);
javascript

useEffect Without Dependencies

When no dependency array is provided, useEffect runs after every render.

useEffect(() => {
  console.log('Runs after every render');
});
javascript

useEffect with Empty Dependency Array

An empty dependency array makes useEffect run only once after the initial render.

This is commonly used for API calls when the component loads.

useEffect(() => {
  console.log('Runs only once on mount');
}, []);
javascript

useEffect with Dependencies

When dependencies are provided, useEffect runs whenever those values change.

This helps control when side effects should be triggered.

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

Common Use Cases

useEffect is commonly used for fetching data from APIs, setting up subscriptions, and working with timers.

It is also used for synchronizing state with local storage or external services.

Data Fetching Example

One of the most common use cases of useEffect is fetching data when a component mounts.

import { useEffect, useState } from 'react';

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

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

  return <div>{users.length} users loaded</div>;
}
javascript

Cleanup Function in useEffect

useEffect can return a cleanup function that runs before the component unmounts or before the effect runs again.

This is useful for clearing timers, cancelling subscriptions, or removing event listeners.

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

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

Common Mistakes

A common mistake is forgetting to add dependencies, which can lead to stale data.

Another mistake is causing infinite loops by incorrectly updating state inside useEffect.

Dependency Array Rules

All values used inside useEffect should be included in the dependency array.

This ensures React knows when to re-run the effect correctly.

Real-World Usage

useEffect is widely used in dashboards, authentication flows, notifications, and real-time applications.

It plays a critical role in integrating React apps with external systems.

Best Practices

Keep effects focused on a single responsibility to avoid complexity.

Always clean up side effects to prevent memory leaks.

Summary

useEffect is essential for handling side effects in React functional components.

Understanding its behavior with dependencies and cleanup functions is crucial for building robust applications.