Understanding the useEffect Hook

 React is primarily used for building user interfaces, where components re-render based on changes in state or props. But real-world applications often need to interact with external systems—fetching data, subscribing to events, updating the DOM, or starting timers. These are known as side effects, and React’s useEffect hook is the tool designed to handle them in functional components.

What is useEffect?

The useEffect hook lets you perform side effects in your component. It's React’s way of combining several lifecycle methods from class components (like componentDidMount, componentDidUpdate, and componentWillUnmount) into a single, unified API.

Syntax:

useEffect(() => {

  // side effect code

  return () => {

    // cleanup code (optional)

  };

}, [dependencies]);

The first argument is a function containing your side effect logic.

The optional second argument is a dependency array that controls when the effect runs.

jsx

Basic Example

import React, { 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>

  );

}

In this example, the document title updates whenever count changes. The useEffect only runs when the count state changes, thanks to the dependency array.

Dependency Array Explained

The second argument of useEffect determines when the effect runs:

No array: Runs after every render.

Empty array ([]): Runs once after the first render (like componentDidMount).

With variables: Runs only when specified dependencies change.

Cleanup Function

If your effect involves something that needs to be cleaned up (like a timer or event listener), return a function inside useEffect:

useEffect(() => {

  const timer = setInterval(() => {

    console.log('Tick');

  }, 1000);

  return () => clearInterval(timer); // cleanup

}, []);

Final Thoughts

The useEffect hook is one of the most powerful and essential features in modern React. It enables functional components to handle side effects and lifecycle events without needing classes. By understanding how and when to use useEffect, you can build more dynamic, responsive, and maintainable applications.

Learn  MERN Stack Training Course

Props in React: Passing Data Between Components

Managing State with useState Hook

Managing State with useState Hook

Understanding the useEffect Hook

Visit Our Quality Thought Training Institute 


Comments

Popular posts from this blog

What Is Tosca? A Beginner’s Guide

Exception Handling in Java