React Lifecycle and useEffect
Today let us look at the React lifecycle and its methods. We will also learn about useEffect and how it is affected by the various lifecycle methods.
1. The React lifecycle represents a component's stages during its lifetime. Each of these stages has its own methods.
2. There are 3 stages in the lifecycle: mounting, updation and unmounting.
3. Mounting refers to the stage when a component gets first loaded. It consists of many methods, the prominent among them are componentWillMount and componentDidMount. The componentWillMount() method is called right before the component is mounted on the DOM. The componentDidMount() method is called right when the component is mounted on the DOM.
4. Updation refers to the stage when the component gets updated with values. Among other methods, it contains the componentShouldUpdate() and componentDidUpdate() methods. The componentShouldUpdate() method decides if the component should or should not be rendered. While the componentDidUpdate() is executed when the component is updated.
5. The final stage called Unmounting performs the cleanup activities. It contains the componentWillUnmount() method.
6. The useEffect() hook runs whenever any external change needs to be performed. It has the following syntax:
useEffect(()=>{}, []). It takes a function and a dependency array as parameters.
7. When no dependency is specified, it runs once, during mounting(componentDIdMount).
8. When a dependency is specified, it runs once during mounting and every time the dependency changes(componentDidUpdate).
9. When the useEffect function returns a value, the useEffect runs once during mounting, executes the code in return first every time the dependency array value changes and then once every time the dependency changes.
Example: Let us assume that count is changed in the component by a useState().
useEffect(()=>{
console.log(“count has updated”);
return()=>{
console.log(`we are in the cleanup – the count is ${count});
};
}, [count]);
Output:
count has updated
we are in the cleanup – the count is 0
count has updated
And the last 2 output statements will repeat every time the count is updated.
10. It is very important in a useEffect, to specify an empty array when we don’t want it to run when a state changes. If no dependency array is specified, the useEffect runs every time no matter what changes in the component. This could be dangerous and expensive if API calls and database updates are being done in the useEffect.Hence, the useEffect should be used with a proper understanding of how it works.
I hope the article has clarified any doubts about the usage of useEffect. Please let me know in the comments if this article was useful to you.