Component Lifecycle🌀 in ReactJS🚀
In React⚛️, component are designed to follow the natural cycle🚲 of life. As everyone goes through a cycle of born, grow and die. Each component in react goes through Mounting, Updating and Unmounting. Below is a good illustration of how react lifecycle works.
Image Source: wojtekmaj
React provides access to certain built-in events/methods called lifecycle🌀 hooks or lifecycle methods. These methods give you opportunities to control and manipulate how a component reacts to changes in the application.
Let’s have a look at each phase in a component lifecycle:
🍀Initialization
This is the first stage in react lifecycle, in this stage🪜 the component is constructed with provided props and default states. This is where we define defaults and initial values for this.props
and this.state
.
🍀Mounting
This is the next state🪜 in React Lifecycle. After you have prepared the basic code requirement, states and props, you need to mount on the browser. This is done via browser DOM. React⚛️ uses virtual DOM to put all the elements into the memory. Note: Child component is mounted before the parent component.
🌿constructor
constructor()👷 method is called when the component is initiated and it’s the best place to initialize our state. The constructor method takes props as an argument and starts by calling super(props)
before anything else.
class Todo extends React.Component {
//Setting the initial state of the Component
constructor() {
super();
this.state = {
task: "",
isCompleted: false,
dateCreated: ""
}
}
}
🌿componentDidMount
This is the final ReactJS hook🪝 method that is executed after the component mounts the DOM. This method is executed after first render and is executed only on client side. This is a great place to set up initial data. Child component's componentDidMount
runs before parent's componentDidMount
. It runs🏃♂️ only once. You can also make the right API calls under this method so that you can retrieve the data the right way.
🌿static getDerivedStateFromProps
This method is called (or invoked) before the component is rendered to the DOM on initial mount. It allows a component to update its internal state in response to a change in props. To update the state -> return object with new values.
For example,
static getDerivedStateFromProps(props, state){
return{
points: 200 // update state with this
}
}
🍀Updating
The third stage🪜 starts when the component has been adopted on the browser. During this phase the component is already inserted into DOM. A component is updated when there is a change in state
and props
React basically has three built-in methods that are called while updating the components.
🌿shouldComponentUpdate
The method tells the program🐱💻 about the state of rendering when it is updated. If new props or rules are being updated, then a rendering can be done or skipped. This is important to code in properly as there are evolving states in the program as well. Updating the method as true/false is the proper approach. The default here is true, which can be changed as per the code.
🌿getSnapshotBeforeUpdate
This hook🪝 is executed right after the render method is called. It has access to props
and state
before the update. It is handy when you want some DOM info or want to change DOM just after an update is made. For example, getting information about the scroll position.
getSnapshotBeforeUpdate(prevProps, prevState){
//capture the scroll position so we can adjust scroll later
if(prevProps.list.length < this.props.list.length){
const list = this.listRef.current;
return list.scrollHeight - list.scrollTop;
}
return null;
}
Value queried from the DOM in getSnapshotBeforeUpdate
will refer to the value just before the DOM is updated. It doesn't work on its own and used in conjunction with the componentDidUpdate
lifecycle🌀 method.
🌿componentDidUpdate
This method is called just after the re-rendering of the component. This hook🪝 has prevProps
and prevState
available. This lifecycle method is invoked after the getSnapshotBeforeUpdate
is invoked.
componentDidupdate(prevProps, prevState, snapshot){
if(condition){
this.setState({..})
}
else{
//do something else o loop
}
}
🍀Unmounting
The final stage🪜 of unmounting is essential as it doesn’t require the component and gets unmounted from the DOM. As the final state🪜, it is designed to produce the outcome via unmounting.
🌿componentWillUnmount
If there are any cleanup actions like canceling API calls or clearing any caches in storage you can perform that in the componentWillUnmount method. You cannot use setState
inside this method as the component will never be re-rendered.
These are the methods that you are most likely come across. I've omitted some deprecated methods or are set to be deprecated in the very near future.
Thanks for reading💗
Reference: