logo
React Hooks - Interview Questions and Answers
What is useEffect, and why is it used?

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

What are Side Effects?

Side effects are actions that affect things outside of the component's render output. Examples include:

  • Data fetching: Making API calls to retrieve data.
  • DOM manipulation: Directly changing the DOM (though React typically handles this).
  • Setting up subscriptions: Listening to events or data streams.
  • Timers: Using setTimeout or setInterval.
  • Logging: Outputting data to the console.

Why Use useEffect?

In functional components, you can't directly perform these side effects within the main body of the component. This is because:

  • React needs to maintain a predictable rendering process.
  • Side effects can cause unexpected behavior if they're not managed properly.

useEffect provides a way to:

  • Run side effects after the component renders.
  • Control when side effects are executed.
  • Clean up side effects to prevent memory leaks or other issues.

How useEffect Works:

useEffect takes two arguments:

  1. A callback function: This function contains the code for your side effect.
  2. An optional dependency array: This array specifies the values that the effect depends on.

Basic Usage :

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

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

  useEffect(() => {
    // This effect runs after every render
    document.title = `You clicked ${count} times`;
  });

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>Click me</button>
    </div>
  );
}

 

Dependency Array:

  • If you provide a dependency array, the effect will only run when the values in the array change.
  • An empty dependency array ([]) means the effect will only run once after the initial render.
  • Omitting the dependency array means the effect will run after every render.

Cleanup Function:

  • If your effect sets up a subscription or timer, you should provide a cleanup function to unsubscribe or clear the timer when the component unmounts or the effect runs again.
  • The cleanup function is returned by the effect callback.
  • useEffect(() => {
      const timerID = setInterval(() => {
        console.log('Tick');
      }, 1000);
    
      return () => {
        clearInterval(timerID); // Cleanup function
      };
    }, []); // Runs only once

In essence :

useEffect allows you to synchronize your component with external systems or perform actions that are not directly related to rendering, while also providing a mechanism for cleaning up those actions.