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.
