UseEffect hook in React and its use cases

UseEffect hook in React and its use cases

React has introduced a lot of hooks and 'useEffect' is one of the important ones as far as the rendering and updation of the component are concerned.

The name 'useEffect' originated from its ability to deal with the side effects of the functionalities that happen outside of the react scope. It means, once you fetch some data from an API it can either return some 500 status code or the data.

Secondly, when some component receives the props that cause the state change and also the rerender of the component takes place. Then 'useEffect' gets called in this scenario as well.

useEffect(()=>{
// getData
axios.get("https://api.github.com/users").then(res=>{
console.log("Response", res)
})
}, [])

It has two parameters,

  1. A callback function that can be used to perform some action

  2. An array to pass the name of the dependent state or parameter

This 'useEffect' hook gets called on every state change and if we don't pass the second parameter as an array, it will go into an infinite loop and can cause a stack overflow.

If we want to restrict the hook to be called only at once during the first render then a blank array should be passed.

The render can be made dependent on some state value change by passing the same state in the array as a dependency.

Also, If some action is to be performed after the removal of the DOM, like eliminating some subscriptions or removing some event listeners then a return call back can also be used in the same hook.

useEffect(()=>{
// getData
window.addEventListener("scroll", callFunction)
}), 
return()=>{
window.removeEventListener("scroll", callFunction)
}
}, [])

Conclusion: The 'useEffect' hook can be used to perform the features as componentDidMount and componentDidUpdate and componentWillUnmount all together in the functional component.

Did you find this article valuable?

Support Ajinkya Chanshetty by becoming a sponsor. Any amount is appreciated!