In this article, I'm assuming that you have at least some knowledge of using React and want to explore React Hooks.
Introduction
useEffect is one of the known hooks in React application. Some call it the “Effect Hook”. This hook allows you to perform side effects in functional components. It handles componentDidMount, componentDidUpdate and componentWillUnmount all in one call.
In case you are not familiar with Side Effect. It is any execution that is outside the scope of the function being executed. We will not cover much about side effect in this article.
Examples of side effects are:
- Fetching data
- Manual DOM Manipulation
- Setting up a subscription
- Updating global variables
Question: When useEffect runs?
By default it usually run after very render. But there are ways to control it. Let's look at how to run code after the component mounts (componentDidMount), after it re-renders (componentDidUpdate) , and before it unmount (componentWillUnmount)
To run it only once after the component has been mounted, you can do it like this.
// Make sure to pass an empty array on the second argument
useEffect(() => {
console.log(‘Component Mounted!’); // This will trigger only once.
}, []);
To run it every time a props/state variable changes, you can add an array of variables to the second argument:
// Pass a variable to the second argument, and every time that variable changes this useEffect will run.
useEffect(() => {
console.log(‘Counter’, counter); // This will trigger every time counter state changes.
}, [counter]);
If you want to do some cleanup when the component unmount, you can do it like this.
useEffect(() => {
// Run on Component Mount
const handleAuthorSubscription = author => {
setAuthor(author);
}
API.subscribeToAuthor(userId, handleAuthorSubscriptionChange);
// Run on Component Unmount
return () => {
API.unSubscribeToAuthor(userId, handleAuthorSubscriptionChange);
};
}, []);
You just need to add a return function to a useEffect, code inside that returned function will get triggered when a component unmount from a DOM. We use this function to do a cleanup just like removing eventListeners, clearInterval, clearTimeout, etc.
Things to remember in useEffect
- First argument is a callback function. Inside of it, we can perform any side effect there and set some data in state variables.
- Second Argument: Array contains data, useEffect will get triggered every time any data of that array changes. Passing an empty array will trigger the useEffect after the component has been mounted.
And that is all I wanted to share with you. This is my very first article. Hopefully you find this article helpful in learning some basics of React Hooks. If you have any question or feedback for improvement, feel free to comment you're all welcome.
Thanks for Reading! :)