×
☰ See All Chapters

React useEffect hook

The function runs when the component is first rendered, and on every subsequent rerender/update. The useEffect function accepts a function as argument.  React first updates the DOM, then calls any function passed to useEffect().

import { useState, useEffect } from "react";

 

function DemoComponent() {

        const [count, setCount] = useState(0);

        useEffect(() => {

                alert(`you clicked ${count} times`);

        })

        return (

                <div>

                        <button onClick={() => setCount(count + 1)}>Click me</button>

                </div>

        );

}

 

export default DemoComponent;

Since the useEffect() functions are run on every subsequent re-render/update, we can tell React to skip a run, for performance purposes, by adding a second parameter which is an array that contains a list of state variables to watch for. This can be done by passing dependencies array as the second argument to useEffect. useEffect function runs on the first render and any time any dependency value changes. If we keep dependency array empty then useEffect function runs only on the first render.

Run at first render and on every subsequent rerender/update

useEffect(() => {

  //Runs at first render and on every render

});

Run at only first render

export default DemoComponent;

 

useEffect(() => {

  //Runs only on the first render

}, []);

Run at first render and when Props or state changes

useEffect(() => {

  //Runs on the first render

  //And any time any dependency value changes

}, [prop, state]);

Run at first render and when count, firstName, lastName value changes

useEffect(() => {

  //Runs on the first render

  //And any time any dependency value changes

}, [count, firstName, lastName]);

Attaching a hook to component removal

When we return a function from function which is passed as an argument to useEffect then that returned function will run before you destroy your component, Meaning removed from the DOM. You can use this function to perform any clean up tasks.

 

import { useState, useEffect } from "react";

 

function DemoComponent() {

        const [count, setCount] = useState(0);

        useEffect(() => {

                alert(`you clicked ${count} times`);

                return () => {

                        console.log(`Unmounted`);

                }

        })

        return (

                <div>

                        <button onClick={() => setCount(count + 1)}>Click me</button>

                </div>

        );

}

 

export default DemoComponent;

 


All Chapters
Author