Understanding the useEffect Hook

 React’s component-based approach focuses on rendering UI based on data and state. However, applications often need to perform side effects—like fetching data, setting up subscriptions, or directly manipulating the DOM. That’s where the useEffect hook comes in.

Introduced in React 16.8, the useEffect hook allows functional components to perform side effects, a feature previously exclusive to class component lifecycle methods like componentDidMount, componentDidUpdate, and componentWillUnmount.

What is useEffect?

useEffect is a React Hook that runs after every render by default. It can be used for tasks like:

Fetching data from APIs

Setting up event listeners

Updating the DOM

Managing timers or intervals

Syntax:

useEffect(() => {

  // side-effect logic

  return () => {

    // optional cleanup

  };

}, [dependencies]);

Basic Example

import React, { useState, useEffect } from 'react';

function Timer() {

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

  useEffect(() => {

    document.title = `You clicked ${count} times`;

  });

  return (

    <button onClick={() => setCount(count + 1)}>

      Clicked {count} times

    </button>

  );

}

In this example, every time count updates, the useEffect runs and updates the document title.

Controlling When useEffect Runs

The second argument to useEffect is the dependency array:

No array: Runs on every render.

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

With dependencies: Runs only when specified values change.

useEffect(() => {

  console.log("Runs only when count changes");

}, [count]);

Cleanup with useEffect

You can return a function from useEffect to handle cleanup, similar to componentWillUnmount:

useEffect(() => {

  const timer = setInterval(() => {

    console.log("Tick");

  }, 1000);

  return () => clearInterval(timer);

}, []);

Final Thoughts

The useEffect hook is essential for managing side effects in functional components. It simplifies the React lifecycle into a single API and gives you precise control over when and how effects run. Mastering useEffect is key to building robust, interactive, and performant React applications.

Learn  MERN Stack Training Course

Functional Components vs Class Components

Props in React: Passing Data Between Components

Managing State with useState Hook

Managing State with useState Hook

Visit Our Quality Thought Training Institute 


Comments

Popular posts from this blog

Understanding the useEffect Hook

What Is Tosca? A Beginner’s Guide

Exception Handling in Java