useEffect Hook in React with Example

In Class component we use componentDidMount(), componentDidUpdate() and componentWillUnmount() methods as component life cycle methods

componentDidMount() get call when our component renders first time on page. And it executed only once when component renders initially with initial value of states we have.

componentDidUpdate() get call every time the value of states get change, So this method executed more than one time.

componentWillUnmount() get call when the component left the page or remove from the page.

Let’s have one example with all three lifecycle method of Class component. Update document title when button is clicked.

Example Class Component Lifecycle methods

All these three methods replaced by useEffect() hook. Let me show you how you can write the same Example using useEffect().

useEffect Example change title

Here you can see useEffect hook has two arguments first argument is function in which you can write your logic and second argument is an array which represents dependency.

Here we pass count as second argument that means the function will executed only when value of count get changed.

useEffect(() => {
        console.log("title set from useEffect")
        document.title=`You clicked ${count} times`
    })

if you skip second argument then first argument function will executed for name state value change also not only for count state.

So the above example covers onComponentDidMount() and componentDidUpdate() methods only.

So let’s have one more example which can help you to understand componentWillUnmount() method logic with useEffect()

useEffect Example to replace componentWillUnmount

You can see in above example we can return function from useEffect() function and that return function will executed when component stops rendering on the page.

So guys you can understand how useEffect can reduce our code length and simplify our coding complexity. In real world application you can write code to fetch data from server using API as below.

Fetch Data from API with useEffect() in React

JsonPlaceholder for API

Install npm axios for API call

Related Posts

Leave a Reply