What is useEffect: It is a react hook which helps to run side effects in the functional components. Side effects are actions that happen outside the normal rendering process, such as:
● Fetching data from an API
● Updating the DOM manually
● Setting up a timer
Syntax:
import { useEffect } from "react";
useEffect(() => {
  return () => {
  };
}, [dependencies]);
The useEffect hooks runs after the component renders. It takes two arguments:
- A callback function
 - An array of dependencies
 
Here, the array can be written in 3 ways.
- Empty dependency array: If it is given as empty dependency array [], the effect runs only once when the component loads.
 
useEffect(() => {
  console.log("Component mounted");
}, []);
This runs only once when the component is first rendered.
- Dependency array: If any variable is given in the dependency array, the effect runs every time that variable changes.
 
useEffect(() => {
  console.log("Count changed:", count);
}, [count]);
Here, it runs every time count updates.
3 Cleanup function: Here, a function can be returned inside useEffect to clean up resources (like timers or subscriptions).
useEffect(() => {
  const timer = setInterval(() => {
    console.log("Running timer...");
  }, 1000);
  return () => {
    clearInterval(timer);
  };
}, []);
This cleans up the timer when the component unmounts.
    
Top comments (0)