React Interview Questions

39 Questions
React.js

React.js

FrontendWeb Development

Question 15

Explain the useEffect hook and provide an example.

Answer:

The useEffect hook is a fundamental hook in React that allows you to perform side effects in functional components. Side effects can include data fetching, subscriptions, or manually changing the DOM, among other things. The useEffect hook lets you run some code after rendering and can also handle cleanup logic when a component is unmounted.

Syntax

useEffect(() => {
  // Code to run after render
  return () => {
    // Cleanup code (optional)
  };
}, [dependencies]);
  • Effect Function: The first argument is a function containing the side effect code.
  • Cleanup Function: This optional function returned from the effect function is used for cleanup.
  • Dependencies Array: The second argument is an array of dependencies that determine when the effect should re-run. If you omit this array, the effect runs after every render. If you provide an empty array ([]), the effect runs only once after the initial render.

Example: Basic Usage

Let's create a simple component that uses the useEffect hook to update the document title whenever the component's state changes.

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

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

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

    // Optional cleanup function (not needed in this simple example)
    return () => {
      // Cleanup code, if necessary
    };
  }, [count]); // The effect depends on the 'count' state

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

export default Counter;

Explanation

  1. State Initialization:

    • const [count, setCount] = useState(0); initializes a state variable count with an initial value of 0.
  2. useEffect Hook:

    • useEffect(() => { ... }, [count]); runs the effect function after every render where count changes.
    • Inside the effect function, document.title = You clicked ${count} times``; updates the document title based on the current count value.
  3. Dependencies Array:

    • The dependencies array [count] ensures the effect runs only when count changes. Without this array, the effect would run after every render.

Example: Data Fetching with Cleanup

Here’s a more complex example where useEffect is used for data fetching, and the cleanup function is utilized to cancel the fetch request if the component unmounts.

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

function DataFetcher() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    const controller = new AbortController();
    const signal = controller.signal;

    async function fetchData() {
      try {
        const response = await fetch('https://jsonplaceholder.typicode.com/posts/1', { signal });
        const result = await response.json();
        setData(result);
        setLoading(false);
      } catch (error) {
        if (error.name === 'AbortError') {
          console.log('Fetch aborted');
        } else {
          console.error('Fetch error:', error);
        }
      }
    }

    fetchData();

    return () => {
      // Cleanup: Abort the fetch request if the component unmounts
      controller.abort();
    };
  }, []); // Empty array means this effect runs only once after the initial render

  if (loading) {
    return <div>Loading...</div>;
  }

  return (
    <div>
      <h1>{data.title}</h1>
      <p>{data.body}</p>
    </div>
  );
}

export default DataFetcher;

Explanation

  1. State Initialization:

    • const [data, setData] = useState(null); initializes the state variable data.
    • const [loading, setLoading] = useState(true); initializes the state variable loading.
  2. useEffect Hook for Data Fetching:

    • The effect runs only once after the initial render because the dependencies array is empty ([]).
    • An AbortController is created to manage the fetch request and allow it to be canceled if needed.
    • The fetchData function fetches data from an API and updates the state with the fetched data.
  3. Cleanup Function:

    • The cleanup function calls controller.abort() to cancel the fetch request if the component unmounts before the request completes.

Summary

The useEffect hook is a versatile tool for managing side effects in React functional components. It allows you to perform tasks like updating the DOM, fetching data, and handling subscriptions in a clean, declarative way. By using the dependencies array and cleanup functions, you can control when effects run and ensure that resources are properly managed.

Recent job openings