How to Use useEffect in React JS: A Beginner-Friendly Guide

By Pavan Vadapalli

Updated on Jul 23, 2025 | 9 min read | 57.12K+ views

Share:

Did you know? Over 52 lakh live websites in India are powered by React! Its widespread adoption makes it the go-to choice for tackling complex API integrations and efficient data management in modern web apps.

useEffect is a React Hook that lets you run side effects in function components, such as fetching data, updating the document, or reacting to state or prop changes. It’s essential for handling logic that runs outside the normal render cycle. 

Understanding useEffect is crucial to building responsive and maintainable React applications. It helps manage API calls, event listeners, and cleanup tasks in a clean, predictable way. 

In this blog, you’ll learn how useEffect in React JS works through clear, practical examples that prepare you for real-world React development.

Want to grow your React skills beyond just the useEffect hook? upGrad’s Software Engineering courses offer hands-on projects, real-world React workflows, and in-depth explorations of components and hooks. Strengthen your front-end foundation with expert mentorship and personalized 1-on-1 guidance.

What is useEffect in React JS?

The useEffect in React JS is the most commonly used hook for building React applications. You use useEffect in React to handle side effects, such as fetching data or updating the DOM. By default, it runs after every render. But you can control when it runs by using a dependency array.

Here’s the syntax you’ll use to get started.

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

  • The first argument is a function that contains a side effect.
  • The second argument is an optional dependency array that determines when the effect should re-run.

If you’re aiming to boost your React skills or grow in your developer journey, these top courses can help you move forward with confidence.

Now that you understand what useEffect in React JS does, let’s explore some of the most common ways you’ll use it in real projects.

Use Cases for useEffect in React JS

Coverage of AWS, Microsoft Azure and GCP services

Certification8 Months

Job-Linked Program

Bootcamp36 Weeks

You’ll often use useEffect to handle tasks that need to run outside the normal rendering flow. These tasks, known as side effects, are everyday in real-world applications. Whether you're working with data, browser APIs, or external services, useEffect helps you manage those actions cleanly and efficiently. Here are some of the most common scenarios where you’ll use it:

  • Fetching data when a component mounts
  • Updating the DOM or document title based on state
  • Setting up event listeners or intervals
  • Subscribing to services like WebSocket or Redux stores
  • Cleaning up before a component unmounts or updates

Build dynamic UIs with confidence. Take the next step after learning JavaScript. The upGrad’s React JS for beginners course will teach you to build reusable components and create a real-world Phone Directory app. Ideal for anyone starting their journey in front-end development.

Also read: Top 8 React JS Free Courses with Certificate Options [2025]

Let’s explore why useEffect in React JS is such a crucial component for building functional components effectively.

Why is useEffect Important in React Functional Components?

React used to rely on class-based lifecycle methods like componentDidMount and componentDidUpdate. With Hooks, especially useEffect, you can achieve the same results in function components, with less boilerplate and more clarity.

You should use useEffect because:

  • It replaces lifecycle methods, without needing to switch to class components.
  • It keeps logic organized. Each effect can be written separately based on specific dependencies.
  • It ensures your app remains reactive by automatically responding to changes in props, state, or context.
  • It simplifies cleanup: With a return function that runs on component unmount or before the effect runs again.
  • It supports modular design. Effects can be split into smaller, purpose-driven Hooks or custom Hooks.

Explore the language behind React. Before building dynamic forms, get confident with JavaScript, the core of all modern web apps. Enroll in the upGrad’s JavaScript Basics from Scratch course and create interactive websites from the ground up.

Also Read: A Complete Guide to the React Component Lifecycle: Key Concepts, Methods, and Best Practices

Now that you understand what useEffect does, let’s break down how the dependency array affects when and how it runs.

Dependency Array in useEffect: What It Means and How It Works?

When using useEffect in React JS, the dependency array helps you control when the effect runs. It’s a powerful feature that makes your component more predictable and efficient. Here’s how it works in different scenarios:

1. Empty Array

If you pass an empty array as the second argument to useEffect, the effect will run only once, after the component mounts, similar to componentDidMount in class components.

Sample Code:

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

Use this when you want the effect to run only once, such as fetching data on initial load.

2. No Array

If you don’t provide any array, useEffect will run after every render, no matter what changes.

Sample Code:

useEffect(() => {
  console.log("Effect ran after render");
});

This is useful for cases where you need to react to any change, but be cautious, as it can lead to unnecessary executions.

3. With Specific Dependencies

By including specific variables inside the array, you can make useEffect run only when those values change. This is the most common and recommended pattern. It helps you avoid redundant runs and keeps performance optimized.

Sample Code:

useEffect(() => {
  console.log("Effect ran because count changed");
}, [count]);

Using the dependency array in useEffect in React JS is key to writing clean, efficient components that behave as expected during state or prop changes.

Also Read: React useCallback Hook: Why, When & How to Use It?

To see how useEffect in React JS works practically, let’s walk through some practical examples and understand how it fits into the component lifecycle.

How to Use useEffect in React JS: Practical Examples and Lifecycle Use

When working with React functional components, knowing how to implement useEffect effectively can save you time and prevent bugs. From mimicking lifecycle methods to fetching data from APIs, useEffect helps manage side effects cleanly and predictably.

Let’s explore real examples where you can use useEffect in React JS, along with code, output, and clear explanations.

Example 1: Fetching Data from an API

import { useState, useEffect } from 'react';

function UserList() {
  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>
  );
}

Code Explanation: In this example, useEffect runs once when the component mounts to fetch user data. After fetching, the response is stored in the user's state and displayed in a list.

Output (UI):

Example 2: Responding to State Changes

import { useState, useEffect } from 'react';

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

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

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

Code Explanation: This useEffect updates the document title every time the count state changes. The effect only applies when the count updates, as it's listed in the dependency array.

Output :

Also Read: React JS Architecture Explained: Explore Step-by-Step Implementation and Key Tools

While useEffect in React JS is powerful, it’s easy to misuse. Let’s look at some common mistakes developers make and how you can avoid them.

Common Mistakes Developers Make with useEffect in React JS

While useEffect is incredibly powerful, it can also lead to bugs or performance issues if not used correctly. When working with useEffect in React JS, it's essential to avoid common pitfalls and follow reliable patterns to keep your components efficient and predictable.

Mistake 1: Forgetting the Dependency Array

If you don’t pass a dependency array, your effect will run after every render, which may cause unwanted side effects, slow your application, and hang your system.

Wrong:

useEffect(() => {
  console.log("Runs on every render");
});

Fix:
Add a proper dependency array to control when the effect should run. This helps you avoid unnecessary executions and ensures the impact only runs when specific values, such as props or state, actually change. It keeps your component efficient, prevents performance issues, and avoids bugs caused by stale data or repeated side effects.

Sample Code:

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

Mistake 2: Using State Updates Without Proper Dependencies

When you use state or props inside a useEffect, you need to include them in the dependency array. If you don’t, React won’t know to re-run the effect when those values change. This can lead to outdated (stale) data being used, causing bugs or unexpected behavior in your app. 

Wrong:

useEffect(() => {
  if (query !== '') {
    fetchData(query); // query is used but not listed
  }
}, []);

Fix:
Always include all variables that are used inside the effect by separating them with commas if there are more than 1.

Sample Code:

useEffect(() => {
  if (query !== '') {
    fetchData(query);
  }
}, [query]);

Mistake 3: Not Cleaning Up Side Effects

When you use useEffect to set up things like event listeners, intervals, timeouts, or subscriptions (such as WebSocket connections), cleanup is crucial. You should remove or cancel these side effects when the component unmounts or before the effect runs again. Skipping cleanup can cause memory leaks, duplicate handlers, or unexpected behavior in your app. 

Wrong:

useEffect(() => {
  window.addEventListener('resize', handleResize);
}, []);

Fix:
Return a cleanup function inside useEffect.

Sample Code:

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

Also Read: React.js vs Node.js: The Battle of JavaScript Frameworks

Let’s see how upGrad can support your journey with useEffect in React JS and front-end development.

How upGrad Can Help You Master React and Front-End Development?

useEffect in React JS helps your components interact with the UI, whether it’s fetching data, syncing with APIs, updating the DOM, or more. From managing dependencies to handling cleanup logic, understanding this hook is key to writing clean, efficient, and responsive React applications.

But understanding how it works isn’t enough. You need to apply it in real scenarios, build components, debug behaviors, and write side-effect logic that scales.

That’s where upGrad can help. Whether you're starting in React or aiming to level up your front-end skills, upGrad’s software development courses guide you through hooks, component lifecycles, and many more through expert guidance and live sessions.

Here are some additional courses to strengthen your frontend development:

Not sure how useEffect in React JS is applied in real-world projects? Connect with upGrad’s expert counselors or drop by your nearest upGrad offline center to discover a personalized learning path aligned with your goals.

Boost your career with our popular Software Engineering courses, offering hands-on training and expert guidance to turn you into a skilled software developer.

Master in-demand Software Development skills like coding, system design, DevOps, and agile methodologies to excel in today’s competitive tech industry.

Stay informed with our widely-read Software Development articles, covering everything from coding techniques to the latest advancements in software engineering.

Reference:
https://trends.builtwith.com/javascript/React

Frequently Asked Questions (FAQs)

1. What’s the difference between useEffect and useLayoutEffect, and when should I use one over the other?

2. How can I prevent unnecessary re-renders and re-executions of useEffect in my React components?

3. When should I use useRef instead of useState inside useEffect?

4. How do I use useEffect to mimic componentDidMount, componentDidUpdate, and componentWillUnmount?

5. How can I manage async operations like API calls in useEffect without running into race conditions or memory leaks?

6. Why do my useEffect dependencies cause infinite loops even when the values don’t seem to change?

7. How can I optimize performance in large React apps that use multiple useEffect hooks?

8. Can I use multiple useEffect hooks in a single component, and is there a best practice for organizing them?

9. How do I handle debounced or throttled state updates with useEffect in a React app?

10. What’s the best way to sync local storage or session storage with React state using useEffect?

11. How do I use useEffect with third-party libraries or DOM integrations like maps, charts, or sliders?

Pavan Vadapalli

900 articles published

Pavan Vadapalli is the Director of Engineering , bringing over 18 years of experience in software engineering, technology leadership, and startup innovation. Holding a B.Tech and an MBA from the India...

Get Free Consultation

+91

By submitting, I accept the T&C and
Privacy Policy

India’s #1 Tech University

Executive PG Certification in AI-Powered Full Stack Development

77%

seats filled

View Program

Top Resources

Recommended Programs

upGrad

upGrad

AI-Driven Full-Stack Development

Job-Linked Program

Bootcamp

36 Weeks

upGrad

upGrad KnowledgeHut

Professional Certificate Program in UI/UX Design & Design Thinking

#1 Course for UI/UX Designers

Bootcamp

3 Months

IIIT Bangalore logo
new course

Executive PG Certification

9.5 Months