useEffect() Variants

Search for a command to run...

No comments yet. Be the first to comment.
A few months ago, I was frustrated with JavaScript. No matter how many tutorials I watched or articles I read, I couldn’t fully grasp its concepts. Asynchronous programming felt like a mystery, closures confused me, and debugging code felt like an en...
You must have visited a lot of websites in your lifetime. And the user experience on the site is Good site performance is sometimes vital for a good user experience (UX). But what is performance, how can it be measured, and how can it be improved? ...

Hooks are functions that let you use the React state and lifecycle events in a functional component. Hooks won't work inside classes. They came into existence to solve many problems created by the class-based components. In class, it was hard to reuse stateful logic between components. But in function, hooks allow us to reuse stateful logic without changing the component hierarchy.
There are many Hooks. Two of the most commonly used are State Hook and Effect Hook. In this post, we will be taking a look at the Effect Hook.
If you have used class-based components in react then you might be knowing about the Lifecycle events like componentDidMount, componentDidUpdate, and componentWillUnmount. The Effect Hook, useEffect, serves the same purpose as these but unified into a single API.
Now we will be using the mighty Effect Hook.
import React, { useEffect } from 'react';
This function will be called on every render of the component.
// called on every render
useEffect(function callMeEveryRender(){
// do something
});
This function will be called when the component will be mounted.
// called only on mount
useEffect(function callMeOnMount(){
// do something
}, []);
This function will be called when the value count changes.
// called when count changes
useEffect(function callMeOnCountChanges(){
// do something
},[count]);
This function will be called on every render of the component and perform the cleanup.
// called when count changes
useEffect(function callMeAndCleanupEveryRender(){
return function foo(){
// do something
}
});
This function will be called when the component will be mounted and perform the cleanup before the component gets unmounted.
// called only on mount and cleanup before unmount
useEffect(function callMeOnMountAndCleanupBeforeUnmount(){
return function foo(){
// do something
}
},[]);
And don't break the rules, if you will then you will be in great trouble and may get into infinity loops.

We have seen how to use useEffect in a React Function Component
I hope this helped you with understanding useEffect! Thanks for reading! Happy Coding!