React.js Component Lifecycle
What is Component Lifecycle in React.js:
Component's lifecycle refers to the series of stages that a component goes through from its initialization to its removal from the DOM.
Developers can apply and conceive different strategies for the lifecycle stages and some operations can be carried out.
Here's an introduction to some of the key lifecycle methods and the stages they correspond to:
Mounting:
constructor(): This is the first method called when a component is initialized.
It's used for initializing state and binding event handlers.
Note that: you need to avoid causing side effects in the constructor.
render(): This method is required and it returns the JSX that represents the component's UI.
componentDidMount(): This method is invoked immediately after a component is mounted (inserted into the DOM).
It's commonly used for fetching data from APIs, initializing third-party libraries, or performing any actions that require interaction with the DOM.
Updating:
componentDidUpdate(prevProps, prevState): We write this method whenever state of component changes or its interface is changed as after this it automatically renders.
It’s meant to trigger actions collateral on the changes that have taken place, might for instance be making a network request or rendering the DOM in response to the change in prop or state.
Unmounting:
componentWillUnmount(): This method is invoked immediately before a component is unmounted and destroyed.
It's often used for cleanup tasks such as removing event listeners or canceling network requests to prevent memory leaks.