top of page
Search

What is Effect hook?

Writer's picture: Titash RoyTitash Roy

Introduction In our previous post, we have discussed about the REACT hooks and the hook to use state values inside a functional component. In this post, we will discuss about one more hook, useEffect().


useEffect

This hook is used to handle side effects in react functional components. Side-effect can be thought to be data fetching, setting up a subscription, and manually changing the DOM in React components. You can think of useEffect Hook as componentDidMount, componentDidUpdate, and componentWillUnmount combined. In the below snippet, useEffect is the hook that is performing the same function as that of a componentDidMount() lifecycle method and calling an API after the DOM element is loaded.

In React, there are two types of side effects: effects with cleanup, effects without cleanup Effects without cleanup: Most common effect, doesn't require manual DOM mutation. It includes, network requests, logging, etc. Effects with cleanup: This effect comprises of the activity, where one needs to make a subscription to an external system. In such case, the DOM element should be cleaned up while un-mounting, to prevent any memory leak. Additional parameters used in useEffect By default, the useEffect hook would run every time the component is rendered. If you want your hook to run only when the parameters associated with the side-effect change, you can provide a second argument – an array of values. If one of the dependencies has changed since the last time, the effect hook will run again. Below is a snippet for the syntax. In the below snippet, the output is an array , which contains randomly generated user objects. The [] at the end, denotes that, the useEffect hook will be called if the array object is not empty.

NOTE: If the side effect is associated with props and state, it should be part of the array in the second parameter. So that, if any of this affected, the useEffect hook will be invoked.


Summary In this post, we have discussed about useEffect hook and what functionality it adds to the functional components. In the future posts, we will discuss about, more frequently used hooks.





17 views0 comments

Recent Posts

See All

Comments


bottom of page