DEV Community

Sajin Joe J
Sajin Joe J

Posted on

useEffect – Interview Questions

Q1. What is useEffect?

  • useEffect is a React Hook that allows us to perform side effects in functional components.
  • Side effects are operations that happen outside the normal rendering process, such as API calls, timers, event listeners, and updating the document title.
import { useEffect } from 'react';

useEffect(() => {
  // 1. Your side effect code runs here

  return () => {
    // 2. Optional cleanup code runs here
  };
}, [dependencies]); // 3. Optional dependency array
Enter fullscreen mode Exit fullscreen mode
  • No dependency array. The effect runs after the first render and after every single re-render.

  • Empty array []. The effect runs only once right after the component mounts (appears on screen).

  • Array with values [prop, state]. The effect runs on the initial mount and re-runs whenever any of the listed values change.

Q2. Why do we use useEffect in React?

  • We use useEffect to handle side effects in React, such as fetching API data, setting timers, adding event listeners, and synchronizing with external systems.
import { useEffect, useState } from "react";

function Products() {

    const [products, setProducts] = useState([]);

    useEffect(() => {

        const fetchProducts = async () => {

            const res = await fetch(
                "https://dummyjson.com/products"
            );

            const data = await res.json();

            setProducts(data.products);
        };

        fetchProducts();

    }, []);

    return (
        <>
            <h2>Products</h2>

            {products.map(product => (
                <p key={product.id}>
                    {product.title}
                </p>
            ))}
        </>
    );
}

export default Products;
Enter fullscreen mode Exit fullscreen mode

Explanation:

  1. Component renders.
  2. useEffect runs.
  3. API request fetches products.
  4. setProducts() updates the state.
  5. React re-renders and displays the products.

Q3. Cleanup function

  • An Effect can return a cleanup function to stop or undo something when the Effect is cleaned up.
useEffect(() => {

    const timer = setInterval(() => {
        console.log("Hello");
    }, 1000);

    return () => {
        clearInterval(timer);
        console.log("Cleanup");
    };

}, []);
Enter fullscreen mode Exit fullscreen mode

When does cleanup run?

  1. Before the Effect runs again when its dependencies change.
  2. When the component unmounts.
  3. In React Strict Mode development, React performs an extra setup and cleanup cycle to help identify bugs.

Top comments (0)