What is useEffect() hook in React Js?

The purpose of the useEffect hook in React Js is to allow us to perform side effects from within the functional component. Now, what are the side effects? Side effects are anything that affects something outside our function scope. They don’t directly target the output value. Some examples of side effects are data fetching, manipulating DOM directly, using timers or reading from local storage, and many more. We can think of useEffect as the combination of componentDidMount, componentDidUpdate, and componentWillUnmount methods of the class lifecycle.

How to use the useEffect hook?

First, we will import the useEffect hook from React. Now we will define it inside our functional component which is Example.js in our case, as shown below. This code also uses the useState hook. You canĀ understand it from here.

Effects without cleanup:

There are side effects that do not hold any memory. So they require no cleanup.

import React,{useState, useEffect} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    useEffect(() => {
        document.title=`Welcome ${like}`
    });
    return (
        <div>
            <button onClick={()=>setLike(like+1)}>Like {like}</button>
         </div>
    )
}
export default Example;

useEffect() hook has two arguments:

  1. a callback function containing the actual code logic which we want to perform as the side effect.
  2. an optional array of dependencies. It causes the useEffect function to run every time there is a change in its value.

In the above code, we did not give any dependency so the function would run after every rendering. In React Js, the component re-renders whenever its state value is updated. So every time we click on the like button, the component will re-render and useEffect would run causing the title to change.

The output would look like this:

Now, consider the code below.

import React,{useState, useEffect} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    useEffect(() => {
        document.title=`Welcome ${like}`
    },[]);
    return (
        <div>
            <button onClick={()=>setLike(like+1)}>Like {like}</button>
         </div>
    )
}
export default Example;

Notice that in line 6, we have added an empty array as the dependency. This causes the useEffect to run only once after initial rendering. So no matter how many times we clicked on the like button, the title will always show the initial value of like.

The output would look like this:

You can also give particular state variables as the dependency by writing them as comma-separated values inside the array. Look at the code below:

import React,{useState,useEffect} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    const [dislike,setDislike]=useState(0);
    useEffect(() => {
        document.title=`Welcome ${dislike}`
    }, [dislike]);
    return (
        <div>
            <button onClick={()=>setLike(like+1)}>Like {like}</button>
            <button onClick={()=>setDislike(dislike+1)}>Dislike {dislike}</button>
        </div>
    )
}
export default Example;

In this code, useEffect will run only when dislike updates. You can see the change in line no. 7.

The output would look like this:

You can observe the title and value of like and dislike.

These are the side effects that don’t need cleanup. But other side effects need cleanup like unsubscribing anything, clearing the timer, or closing the socket to avoid memory leak. Look at this code below.

Effects with cleanup:

import React,{useState, useEffect} from "react";
const Example = () => {
    const [like,setLike]=useState(0);
    useEffect(() => {
        const id = setInterval(()=> {
          console.log('Clicked'+like);
        }, 1000);
        return () => clearInterval(id);
    }, [like]);
    return(
        <div>
            <button onClick={()=>setLike(like+1)}>Like {like}</button>
         </div>
    )
}
export default Example;

In this code, there is a return function in line 8 that cleans up the timer every time the value of like changes and starts it from the beginning.

The output would look like this:

We can notice that Clicked0 is printed 5 times. Then when we click the like button the timer starts from the beginning. As a result, Clicked1 is printed 8 times. Following this, Clicked2 is printed 4 times. It will continue till we click the like button again.

This was it for the useEffect() hook in ReactJS.

Conclusion:

  • useEffect() runs every time the component renders when we do not provide any dependency.
  • When we provide an empty array as the dependency, useEffect() runs only once after initial rendering.
  • If we provide state or prop variable as the dependency then useEffect runs when those variable updates.
  • Side effects may or may not require cleanup.

You can go through theĀ official documentation for more examples.

Leave a Reply

Your email address will not be published. Required fields are marked *