useEffect hook

Hooks were introduced in React v16. Hooks makes the developer's life very easy because of its simple syntax and power.

useEffectis one of the most important and popular hooks

So What is useEffect

useEffect hook in React is used for handling side effects in functional components. It allows you to perform actions in your components in response to certain events, such as when the component mounts, updates, or unmounts.

mounts This event occurs when a React component is first added to the DOM (Document Object Model). In other words, it happens when the component is rendered for the first time.

unmounts This event occurs when a React component is removed from the DOM. It happens when the component is no longer being rendered or is being replaced by another component.

useEffect is always called once after the component is mounted.

Without the dependancy array [ ] will always be called again when any state is updated inside the component.

Let's Code

Import useEffect

import React, { useEffect } from 'react';

Declare your functional component

 function MyComponent(){
// component logic 
return(
    <div>
    {/* Your component JSX goes here */}
    </div>
     )
}

Use the useEffect hook

function MyComponent() {
  useEffect(() => {
    console.log('Component mounted');
    return () => {
      console.log('Component unmounted');
    };
  }, []); // Empty dependency array means it only runs once on mount
}

We can also use multiple useEffect hooks to watch different variables and act on them differently.

Let's create a small project using React and useEffect for an absolute beginner

npx create-react-app useEffectExample
cd useEffectExample
import React, { useEffect, useState } from "react";
const App =()=>{
  const[count, setCount] = useState(0)
  useEffect(()=>{

    // mounting
    const Increment = ()=>{
        setCount((preCount)=>preCount + 1);
    }

    const intervalId =  setInterval(Increment,1000);

    // unmount
    return(()=>{
        clearInterval(intervalId);
    });

},[]);
    return(
        <div className="App">
         <h1>Count {count}</h1>
        </div>
    )
}
export default App;

This example sets up a simple React app with a functional component (App) that uses useState to manage the count state and useEffect to update the count every second. The useEffect hook sets up an interval that increments the count, and the cleanup function ensures that the interval is cleared when the component is unmounted.

Thank you for reading my content. Be sure to follow and comment on what you want me to write about next 🤓

Did you find this article valuable?

Support Saurabh verma by becoming a sponsor. Any amount is appreciated!