React Interview Reference

Back to home

useEffect Hook

The useEffect hook lets you perform side effects in functional components.

Basic Usage

useEffect runs after every render by default.

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

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

  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {
    // Update the document title using the browser API
    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

Control when the effect runs by providing a dependency array.

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

function Example({ id }) {
  const [data, setData] = useState(null);

  // Only re-run the effect if id changes
  useEffect(() => {
    const fetchData = async () => {
      const response = await fetch(`https://api.example.com/posts/${id}`);
      const data = await response.json();
      setData(data);
    };

    fetchData();
  }, [id]); // Dependency array

  if (!data) return <div>Loading...</div>;

  return <div>{data.title}</div>;
}

Cleanup Function

Return a function from your effect to clean up resources.

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

function ChatRoom({ roomId }) {
  useEffect(() => {
    // Connect to the chat room
    const connection = createConnection(roomId);
    connection.connect();

    // Cleanup function that runs before the effect runs again
    // or when the component unmounts
    return () => {
      connection.disconnect();
    };
  }, [roomId]);

  return <div>Connected to {roomId}</div>;
}

Empty Dependency Array

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

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

function OnlyOnce() {
  useEffect(() => {
    // This runs once after the initial render
    console.log('Component mounted');

    return () => {
      // This runs when the component unmounts
      console.log('Component will unmount');
    };
  }, []); // Empty dependency array

  return <div>I only log on mount and unmount</div>;
}

Common Interview Questions

  • ?
    What is the difference between useEffect and useLayoutEffect?
  • ?
    How do you handle cleanup in useEffect?
  • ?
    What are the common pitfalls when using the dependency array?
  • ?
    How do you handle async operations in useEffect?
  • ?
    How does useEffect differ from componentDidMount, componentDidUpdate, and componentWillUnmount?