React 16.8 comes bearing with gifts such as Hooks and React community couldn't be happier and why won't they be as Hooks gives the developer to create functional components with the power of Class components.
Some of the famous hooks are
- State Hook
- Effect Hook
- Context Hook and so on.
But do you really understand them? Let's talk about the Effect Hook
in this article and we will try to understand when and how to use them.
Using Effect Hooks
As mentioned in the document
The Effect Hook lets you perform side effects in function components
let's talk about what are these side effects? Imagine you are making a web app where you are needed to fetch
some data from the server or set up a subscription using WebRTC
these are some examples of side effects.
In the above example where you are fetching some data from API does not need cleanup means you can execute the function and forget about it. But the later one where you are subscribing needs the cleanup where you have to write some addition line so that every time your component unmounts the cleanup happens and your resources are not wasted up.
let's talk about the Effects without Cleanup
For using Effects in our React functional component we use useEffect
Hook
useEffect (()=>{
console.log("Something Happened")
})
Now useEffect
accepts two arguments one is a callback function and one is an array.
Case 1
In this, we won't pass the second argument, and let's see what happens.
useEffect (()=>{
console.log("Something Changed")
})
Result: Every time our components render the useEffect
Hook gonna run and we can see the text Something Changed
in the console.
Case 2
In this, we will pass an empty array as the second argument [ ]
, and let's see what happens.
useEffect (()=>{
console.log("Only Once")
},[ ])
Result: This time useEffect
Hook gonna run on mounting/ unmounting of our component and we can see the text Only Once
in the console for only one time.
Case 3
In this, we will pass an array containing a state value as the second argument [ someState]
, and let's see what happens.
const [someState , setSomeState] = useState();
useEffect (()=>{
console.log("State Changed")
},[someState ]);
Result: This time useEffect
Hook gonna run when the value of the someState
changes of our component and we can see the text State Changed
in the console when we change the state.
Enough theory let's see some code now.
Above all cases are used in this Play around with the code to get to know more about the useEffect
.
Now let's talk about the Effects with Cleanup
These are tricky ones, we already have seen the examples of hooks with clean up but let's see the code part which is provided in an official document, and try to understand it.
function FriendStatus(props) {
const [isOnline, setIsOnline] = useState(null);
useEffect(() => {
function handleStatusChange(status) {
setIsOnline(status.isOnline);
}
ChatAPI.subscribeToFriendStatus(props.friend.id, handleStatusChange);
// Specify how to clean up after this effect:
return function cleanup() {
ChatAPI.unsubscribeFromFriendStatus(props.friend.id, handleStatusChange);
};
});
if (isOnline === null) {
return 'Loading...';
}
return isOnline ? 'Online' : 'Offline';
}
As you can see we are returning a function this is called clean up function
. This is an optional cleanup mechanism for effects so that when your component had been unmounted from the DOM tree it also unsubscribes to the FriendStatus
. As we already know that effects run with every render so this is important to clean up from the previous render also.
Let's Wrap up
So, we learned three ways how useEffect can be used and we also learned that some effects need cleanups while others don't.
If you learned something or liked my content follow me on Twitter.
or
follow me on Hashnode Ashish maurya