DEV Community

Ramesh Vishnoi
Ramesh Vishnoi

Posted on • Edited on

useEffect Simplified

useEffect hook was introduced in functional class paradigm in React. useEffect is most used hook, you can use it to make network call, preform calculation, listen for a particular state change and for cleanup of component.

Let's understand useEffect function definition first -

useEffect(() => {

    return () => {
        // cleanup function
    }
},[])
Enter fullscreen mode Exit fullscreen mode

This hook accepts callback function as 1st argument and dependency array as 2nd argument.
Inside callback function, you can return a function which will get triggered as cleanup function.

2nd Argument - Dependency array is tweak for different behaviour.

Before going to into useEffect, lets understand first when a component is mounted and unmounted.

A component is mounted when it is part of render logic.

const Profile = () => {
    return (
        <div>Profile Component</div>
    )
}

const App = () => {
    const mount = false;
    return (
        <div>
            {
                mount ? <Profile/> : null
            }
        </div>
    );
}

Enter fullscreen mode Exit fullscreen mode

Here Profile component is mounted only when mount flag is true and unmounted only when it is removed from render.

Case 1 - Empty dependency array

useEffect(() => {
    return () => {

    }
},[])
Enter fullscreen mode Exit fullscreen mode

Here, callback function will be triggered when component is mounted and cleanup function will be triggered with component is unmounted.

This is similar to componentDidMount and componentDidUnMount from class based components from pre React 16.

Case 2 - With Dependency array

const App = () => {
    const [count, setCount] = useState(0);
    const [streak, setStreak] = useState(0);

    useEffect(() => {
        // This will be triggered when count state is changed
        return () => {

        }
    },[count])

    useEffect(() => {
        // This will be triggered when count streak is changed
        return () => {

        }
    },[streak])


    useEffect(() => {
        // This will be triggered when count or streak streak is changed
        return () => {

        }
    },[count, streak])

    return (
        <div>
           <p>This is count : {count}</p>
           <p>This is streak : {streak}</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Case 3 - No Dependency array

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

    useEffect(() => {
        // This will trigger on every render
        return () => {

        }
    })

    return (
        <div>
           <p>This is count : {count}</p>
           <p>This is streak : {streak}</p>
        </div>
    );
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)