DEV Community

Cover image for Mastering the useEffect API
Mark Abeto
Mark Abeto

Posted on

Mastering the useEffect API

The Hooks API is a great feature that was added in version v16.8 last february and change the way on how we write our React Apps. We now write more functional components instead of class components. We don't need to bind any more functions inside the constructor because of the functional components. So today we demystify the useEffect API.

Basically what this Hook does is you need to render the component after you've done something. It is mostly used for calling or fetching data from an API or your web service and you need to do something after DOM Updates.

The useEffect Hook is basically componentDidMount, componentDidUpdate, and componentWillUnmount combined.

First, we demonstrate the componentDidMount equivalent to the useEffect API.
componentDidMount

useEffect componentDidMount

You can see the difference between the two examples. The second example has lesser lines than the first one and is more readable than the first we get rid of the constructor method. The key thing here is the second parameter in the useEffect method an empty array what this means is that we only run the first parameter of the useEffect Hook or the callback function once or we call it only on the first render of the component.

Second, we demonstrate the componentDidUpdate equivalent to the useEffect API.
componentDidUpdate

useEffect componentDidUpdate

The key thing to remember here is that we pass the searchTerm on the array in the second parameter of the useEffect Hook. When the searchTerm value changes we run the callback function on the useEffect Hook. If the current value of searchTerm is "a" and the new value on the next render is "ab" the useEffect hook compares the value and evaluates that its different and proceedingly calls the callback function.

Lastly, we demonstrate the componentWillUnmount equivalent to the useEffect API.

componentWillUnmount

useEffect componentWillUnmount

Inside the callback function on the first parameter on the useEffect Hook, we return a function which is called a Cleanup so that we avoid memory leaks in our app in this example we remove event listeners in the dom and clear the timeout. This Timeout Component Helper that I made is Higher-Order Component that redirects the user to the base path if the components reach if the user does not trigger any events on the events array. The Timeout which in this case is 600 seconds or 5 minutes. Feel free to use this in your projects or add some functionality to it.

Thanks for reading this post.

Have a Good Day Everyone 😃.

Top comments (0)