DEV Community

Cover image for React useEffect() Hook Made Easy
Ezhil Abinaya K
Ezhil Abinaya K

Posted on

React useEffect() Hook Made Easy

useEffect Hooks
The useEffect Hook allows you to perform side effects in your components.Some examples of side effects are: fetching data, directly updating the DOM, and timers.useEffect accepts two arguments. The second argument is optional.useEffect(<function>, <dependency>)
Syntax:

useEffect(() => {
    // Code to run on each render
    return () => {
        // Cleanup function (optional)
    };
}, [dependencies]);
Enter fullscreen mode Exit fullscreen mode

Effect function: This is where your side effect code runs.
Cleanup function: This optional return function cleans up side effects like subscriptions or timers when the component unmounts.
Dependencies array: React re-runs the effect if any of the values in this array change.
Types of React Hook
1. Runs after every render(No dependency array)

useEffect(() => {
  console.log("Runs after every render");
});
Enter fullscreen mode Exit fullscreen mode

2. Runs only once (on initial render)(Empty dependency array [])

useEffect(() => {
  console.log("Runs only once");
}, []);
Enter fullscreen mode Exit fullscreen mode

3. Runs when a specific value changes (Dependency array [value])

useEffect(() => {
  console.log("Count changed");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

Component Lifecycle (Functional Components)
1. Mounting (Component is Created)
The component is created and added to the DOM.It renders for the first time.We usually fetch API data or initialize values here.

useEffect(() => {
  console.log("Component Mounted");
}, []);
Enter fullscreen mode Exit fullscreen mode

2. Updating (Component Re-renders)
It Happens when state or props change.React updates the UI with the latest data.useEffect() can run again if its dependencies change.
Example: In a Counter App, clicking the button updates the count and the UI.

useEffect(() => {
  console.log("Count Updated");
}, [count]);
Enter fullscreen mode Exit fullscreen mode

3. Unmounting (Component is Removed)
The component is removed from the DOM. It is Used to clean up timers, event listeners, or subscriptions.

import { useState } from "react";
import UseEffectDemo from "./UseEffectDemo";

function App() {
  const [show, setShow] = useState(true);

  return (
    <>
      <button onClick={() => setShow(!show)}>
        Toggle Component
      </button>

      {show && <UseEffectDemo />}
    </>
  );
}

export default App;
//API calling...
Interval function...
Interval function...
Interval function...
When you remove the component, you'll see:
Component unmounted...
Enter fullscreen mode Exit fullscreen mode

References
https://www.w3schools.com/react/react_useeffect.asp
https://www.geeksforgeeks.org/reactjs/reactjs-useeffect-hook/

Top comments (0)