Skip to content

What is useEffect Hook in React with Simple Example

useEffect

So we learned about useState() hooks in previous article. Today we are going to learn about most important reactjs hooks which is useEffect().

Hooks are a new addition in React 16.8. They let you use state and other React features without writing a class.

What is useEffect Hook in React?

The useEffect() hook allows us to run side effects on your functional components. Side effects is a general concept about how functions behave which are not predictable. A function is supposed to have side effects when it tries to change something outside of its body. useEffect() also can perform data fetching side-effect using API.

React useEffect is a function that runs for 3 different lifecycles of React components. These lifecycle methods are following

  1. componentDidMount
  2. componentDidUpdate
  3. componentWillUnmount

First Understand with Class Example

import React, { Component } from 'react'

class CounterOneClass extends Component {
    constructor(props) {
        super(props)
        this.state = {
            count: 0
        }
    }
    componentDidMount() {
        document.title = `Clicked ${this.state.count} times`
    }
    componentDidUpdate(prevProps, prevState) {
        document.title = `Clicked ${this.state.count} times`
    }
    render() {
        return (
            <div>
                <button onClick={() => this.setState(
                    { count: this.state.count + 1 })}>
                    Click {this.state.count} times
                </button>
            </div>
        )
    }

export default CounterOneClass

As you have a look at the code above, for update the document title we write the code two times, as soon as in componentDidmount() and as soon as in componentDidUpdate().

This is because in many times we want to run the same side effect in any case whether the component was just mounted or updated. Conceptually we want this to happen after every render, but the React class components don’t do this. have such a method. We could extract a separate method, but we’d still have to call it in two places.

Now let’s see how we can use same example in useEffect reactjs Hooks.

useEffect Example

import React, { useState, useEffect } from 'react';

export function CounterOneHook() {
    const [count, setCount] = useState(0);

    useEffect(() => {
        document.title = `You clicked ${count} times`;
    });

    return (
        <div>
            <p>You clicked {count} times</p>
            <button onClick={() => setCount(count + 1)}>
                Click me
            </button>
        </div>
    );
}

As you see above when we are going to work with reactjs hooks our code is very short and simple.

useEffect() hook has a 2 arguments

useEffect(callback[, dependencies]);
  • The callback is the function that contains the side effect logic. The callback runs right after the changes are pushed to the DOM.
  • dependencies is an optional array of dependencies. useEffect() only executes the callback if the dependencies will be change between the rendering.

Lets understand the our example

We declare the count state variable and then tell React that we need to use an effect. Also we pass a setCount function to the useEffect() hook. This function that we pass is our effect. Within our effect, we set the document title using the document.title browser API.

We can read the last count into the effect because it’s within the scope of our function. Also when React renders the component, it remembers the effect which we used and then runs our effect after updating the DOM. This happens on every render, including the first.

As you notice here useEffect is going to be different on every render of the DOM. To resolve this issue we can use bracket []. You have to just replace following code in above example so this will render only at a time of component mounted

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, []);    
// add empty brackets here. Runs ONCE after initial rendering

Suppose you want to use only on dependent variable in the useEffect Hook. Means when the count variable updates, the effect will run again. In that time you can replace following code

useEffect(() => {
  document.title = `You clicked ${count} times`;
}, [count]);
// Runs ONCE after initial rendering
// and after every rendering ONLY IF `prop` or `state` changes

Others ReactJs Hooks

Conclusion

In this article we learn about reactjs useEffect with side effect understanding with the help of class and functional components. Hope you will understand now what is useEffect. In next tutorial or article we will understand the useEffect example with json search api.