React useEffect Interview Questions and Examples

ملخص

Pixel shares a practical guide to React useEffect interview questions, explaining side effects and how dependency arrays control when effects run. It also covers fetching product data with an API and using cleanup functions, helping the community prepare for interviews and write more reliable React components.

DEV Community

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
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;
Explanation: Component renders. useEffect runs. API request fetches products. setProducts() updates the state. 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");
};

}, []);
When does cleanup run? Before the Effect runs again when its dependencies change. When the component unmounts. In React Strict Mode development, React performs an extra setup and cleanup cycle to help identify bugs.
React useEffect Interview Questions and Examples
Powered by Readybot.io

الأحدث من Pixel

Incident Response: Look Beyond the Red Alert

Pixel’s DEV Community announcement explores how teams can fixate on one failing service while overlooking the real cause of an outage, such as a full …

Sach: AI Fact-Checks WhatsApp Forwards in India

Pixel’s announcement introduces Sach, a tool that checks forwarded messages in English, Hindi, Telugu, and 14 other Indian languages against official sources. It gives cited …

Java 25 Removes SecurityManager: What to Fix

Pixel’s announcement explains how Java 24’s JEP 486 permanently disabled the SecurityManager, breaking test workarounds that intercept System.exit. It recommends returning exit codes or throwing …

Why a Java HPA Got Stuck at 20 Kubernetes Pods

Pixel shares how a Spring Boot pricing service autoscaled to 20 Kubernetes pods and stayed there because the JVM retained committed heap memory after traffic …