Development

Using the React Hook useEffect

React’s useEffect hook has to be one of the most useful React hooks of all. With applications leaning more toward functional components (as it is undeniably easier to read, maintain, and test), useEffect hooks are generally used to handle side effects of functional components. The hook provides components with the power to handle side effects or effects invoking in functional components much like the lifecycle hooks on a class component.

What are side effects?

To put it simply, side effects are all the component modifications that can’t happen or will happen only after the rendering process is done. This would include asynchronous operations, manual DOM modifications, or subscriptions. With the traditional class components, these were usually handled by lifecycle methods like componentDidMount().

Basic Usage of useEffect()

We know that useEffect, similar to react lifecycle hooks, is used for handling/invoking side effects. This sounds complicated but is completely the opposite. Let’s look at an example.

const [likes, setLikes] = React.useState(0);

 React.useEffect(() => {
    alert(likes + 'likes');
}, [likes]);

In the above example, whenever there is a change in the Likes value, the useEffect hook will run. It will also run at the first render since we’ve an array parameter.

If no parameter is provided, it will run on every render. So just like the lifecycle hooks, we can time the useEffect function to run our events.

But, they are always executed after render. However, like I mentioned earlier, we can choose to run it on the first render, on all render, or on first render or when the parameter prop changes.

useEffect() with Cleanup

While there is some code we need to run after DOM has been updated that doesn’t require cleanup, there is also some code that would need cleanup before the component is unmounted.

For that, we’d use the cleanup function, which will help us clean up the useEffect invoked code to make sure there’s no memory leak and the application is optimized. Let’s look at the example below.

Although it’s not a traditional usage of the cleanup hook, this could be the perfect example for explaining its caliber. We are taking the likes from an external API, storing it locally for an instance, and then updating it on the component unmount with the cleanup hook.

const [likes, setLikes] = React.useState(0);

const updateLikes = () => {
       setLikes( likes++ );
 }
React.useEffect(() => {
    // Get initial likes from API.
    setlikes( LikesAPI.getLikes() );
    
    
  
    // update the likes on API on unmount:
    return () => {
      LikesAPI.updateLikesAPI(likes);
    };
 
}, []);

As you can see, the Cleanup() function (which could be just be a return statement) is updating the API anytime we’re done with the likes component.

Contrary to how it looks, it is really easy to understand useEffect hooks. They can be used multiple times on multiple instances. Just be careful when using them and ensure proper cleanup is done. This way, you don’t end up with an unorganized and unoptimized application.

Comments

Have a comment?

Your email address will not be published.

accessibilityadminaggregationanchorarrow-rightattach-iconbackupsblogbookmarksbuddypresscachingcalendarcaret-downcartunifiedcouponcrediblecredit-cardcustommigrationdesigndevecomfriendsgallerygoodgroupsgrowthhostingideasinternationalizationiphoneloyaltymailmaphealthmessagingArtboard 1migrationsmultiple-sourcesmultisitenewsnotificationsperformancephonepluginprofilesresearcharrowscalablescrapingsecuresecureseosharearrowarrowsourcestreamsupportunifiedupdatesvaultwebsitewordpress