DEV Community

VIDHYA VARSHINI
VIDHYA VARSHINI

Posted on

useEffect in React

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]);


Enter fullscreen mode Exit fullscreen mode

The useEffect hooks runs after the component renders. It takes two arguments:

  1. A callback function
  2. An array of dependencies

Here, the array can be written in 3 ways.

  1. 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");
}, []);

Enter fullscreen mode Exit fullscreen mode

This runs only once when the component is first rendered.

  1. 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]);

Enter fullscreen mode Exit fullscreen mode

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);
  };
}, []);

Enter fullscreen mode Exit fullscreen mode

This cleans up the timer when the component unmounts.

Top comments (0)