In: Computer Science
How do React lifecycle methods work (what does each method do and when)?
React lifecycle methods is a progression of functions that occur from the introduction of a React part to its demise.
Each part in React experiences a lifecycle of functions, experiencing a pattern of birth, development, and demise.
Mounting – Birth of component
Update – Growth of component
Unmount – Death of component
Common React Lifecycle Methods are:
render()
The render() strategy is the most utilized lifecycle method. render() is the main required strategy inside a class part In React.it handles the rendering of segment to the UI. It occurs during the mounting and updating of the segment.
componentDidMount()
componentDidMount() is called when the part is mounted and prepared. This is a decent spot to start API calls if need to stack information from a remote endpoint.
In contrast to the render() method, componentDidMount() permits the utilization of setState(). Calling the setState() here will state state and cause another rendering yet it will occur before the program updates the UI. This is to guarantee that the client won't perceive any UI refreshes with the twofold rendering.
componentDidUpdate()
This lifecycle technique is conjured when the update occurs. The most widely recognized use case for the componentDidUpdate() technique is refreshing the DOM because of prop or state changes. Can call setState() in this lifecycle, yet need to enclose it by a condition to check for state or prop changes from past state. Wrong utilization of setState() can prompt an endless circle.
componentWillUnmount()
As the name recommends this lifecycle method is called not long before the segment is unmounted and obliterated. In the event that there are any cleanups activities that you would need to do, this would be the correct spot.