ReactJS is one of the leading JavaScript frameworks out there. It gives developers the ability to create responsive websites with a modern user interface.
To give power in the hands of the developer, it uses plenty of techniques including hooks! Hooks are added to React in its 16.8 updates.
In this article, we will cover how to make proper use of useEffect in ReactJS.
But, before we go there, let’s first try to understand Hooks and how they work.
If you didn’t know about Hooks yet, then it might be for the reason that Hooks in ReactJS are optional. This means that you can create a fully-functional reactJS app without the need to use a hook. But, Hooks gives developers access to direct API, which you can use on different React concepts including context, refs, pros, lifecycle, and state. With hooks, you can combine each one of them to create powerful effects on your React-powered site.
In short, you can use Hooks to solve problems in ReactJS when managing huge applications composing of thousands of components. Hook does it by providing reusable behavior to the component.
This means that you can use add behaviors like connecting to the store using the Hooks. By doing so, you can separate stateful logic and test it independently. You can do other things using Hooks to fetch data, manually change DOM, or fetch subscriptions! Also, Hooks
However, Hooks are not a replacement for Classes!
In the end, you can write Hooks to get access to functional components and then implement class-based features there.
The benefits of Hooks can be summarized as below:
With a complete understanding of Hooks and what they let you do, let’s explore the two types of Hooks: the State Hook and the Effect Hook.
As we are focusing only on Effect Hook, we will cover State Hook briefly. Let’s first see an example of State Hook, useState, below. The example is taken from the ReactJS official documentation.
import React, { useState } from 'react'; function Example() { // Declare a new state variable, which we'll call "count" const [count, setCount] = useState(0); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
The first thing that you will notice about it is that it is compact and easy to read. If you try to do it equivalently in-class component, then you have to write more code! Also, the behavior will be tightly fit the class and is not reusable elsewhere.
Also, the example above simply has a counter set to 0, which is incremented the user clicks.
Note: You can use Hooks in functional components and not class-based components.
The steps to define a State Hook include
Finally, we are at Effect Hook!
So, what purpose do they serve?
Well, the useEffect() can be termed as a useful way to call side effects operations on the React components. So, it may sound similar to the different lifecycle steps of the React components such as componentDidMount, componentWillMount, and componentDidUpdate. The useEffect() gives you a unified way to handle those.
Sounds confusing? Let’s quickly check out an example that utilizes useEffect(). The example is taken from the official ReactJS documentation.
import React, { useState, useEffect } from 'react'; function FriendStatus(props) { const [isOnline, setIsOnline] = useState(null); function handleStatusChange(status) { setIsOnline(status.isOnline); } useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; }); if (isOnline === null) { return 'Loading...'; } return isOnline ? 'Online' : 'Offline'; }
Here the useEffect() function is used to subscribe to the friend’s online status and unsubscribing from it.
The exact code that does it is as below:
useEffect(() => { ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange); return () => { ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange); }; });
Also, you can pile up more effects on the component as per your requirement. To do so, you need to create another useEffect() function within the component and then define it accordingly.
But, what about the organization of multiple useEffect()? Well, you can decide the organization based on the lifecycle of the component.
useEffect() is also useful after the DOM is updated. This means that you can use it to run additional code that does not require cleanup. For instance, you can run a network diagnostic or log changes into the system after the main operations are done. That’s why useEffect() is known as a side effect!
Do you remember the counter-example that we shared above? Well, let’s see how we can use useEffect() there and modify it. Also, again, the code is taken from the official documentation.
import React, { useState, useEffect } from 'react'; function Example() { const [count, setCount] = useState(0); useEffect(() => { document.title = `You clicked ${count} times`; }); return ( <div> <p>You clicked {count} times</p> <button onClick={() => setCount(count + 1)}> Click me </button> </div> ); }
Here, we use the useEffect() to tell the DOM to render how many times we have clicked. Also, it should be noted that the useEffect() is called within a component and hence the state variable is accessible to the effect itself. This way, the variables can be in scope and the Effect functions do not have to worry about the out of scope errors.
In short, you can think of useEffect as a way of what happens after the render gets completed.
We hope that you understood useEffect in ReactJS. It might sound a little complex, and it is okay if you do not want to use it right away in your application development. As mentioned already, Hooks are completely optional, and this should mean that useEffect() Hook is also optional.
Also, there are some Rules of Hooks that you need to follow to use it effectively. To know the rules, we recommend checking out their official documentation!