React Lifecycle Methods
Component Lifecycle methods help React to adapt quickly whenever the user interaction occurs or the Component updates. In order to understand their usage better, we can separate them into three major parts, create, update, destroy (or Mounting, Updating, Unmounting), just like the human beings’ lifecycle is divided into three major parts such as birth, change, and death, respectively. To transfer these functionalities into practical use, we can say that whenever the user opens a web page or creates something, the Lifecycle method responsible for creation is invoked, whenever the user changes anything, the Lifecycle update method is triggered. When the user deletes something or closes down a window, the delete method is called. These methods are called at specific times in Components, before or after render
, they are not necessary, but they help the Components run smoothly and organize methods in a logical way.
Mounting
If we differentiate Lifecycle methods before and after therender
phase, we can say that only one method is called, static getDerivedStateFromProps
just after theconstructor
is triggered. The Mounting phase consists of two Lifecycle hooks, the static getDerivedStateFromProps
(before render
) and componentDidMount
(after render
). Why is it important to call these methods at a specific time, before or after render
? It’s about user experience which is enhanced by the way the page loads. If we would call componentDidMount
before render
, it would require more loading time while this method is usually responsible for getting data from the back-end, running asynchronous requests like fetching data or updating, which can be time-consuming. We don’t want the user to wait this long, that’s why we first offer the user to observe whatever render
returns, then fetch some data from the server, thus saving time. static getDerivedStateFromProps
runs before render
, and, as the name suggests, it has access to any state and props, and the state can be changed just before the component renders. It’s the only hook to run before render
render and before JSX is rendered into the DOM.
componentDidMount(){
this.setTime()
}
setTime = () => {
this.setState({ time: new Date(Date.now())});
}
Updating
Anytime when the user interacts with Component and changes some data, it re-renders or updates the props and state. static getDerivedStateFromProps the
method is called not only when Component is created, but also when it is updated. We already covered that this method gives us access to any props and state that can be changed or returned intact before render
runs. After that, if look at the scheme above, we can see that at this stage another method is triggered, such as shouldComponentUpdate
and it runs just before re-rendering. As the name of the method prompts, it returns true
or false
Boolean values while we don’t want the Component to re-render if no change has been made. So, anytime when shouldComponentUpdate
returns false
, it doesn’t make unnecessary re-rendering (updating) and, vice versa, the Component only updates when this method returns true
, meaning that the state has been altered. This one answers to “why should component update when there is no change in the state” rhetorical question. Just after answering this question, React displays data by rendering JSX into DOM. Before entering the final stage of the update, React runs another method called getSnapshotBeforeUpdate
which takes a “picture” or snapshots of minor changes just before updating such as mouse cursor or scroll position. After running all these methods, the final stage of the update is called, componentDidUpdate
. It runs only after the Component is re-rendered and updated, taking with it both the previous and the current props and states and using them to make changes in libraries if necessary.
componentDidUpdate(prevProps, prevState) {
if (prevProps.data !== this.props.data) {
// do something
});
}
}
Unmounting
It is always a good idea to clean up after yourself. With this concept in mind, the final Lifecycle hook is triggered, componentWillUnmount
. This one is responsible for deletion and clearing of all the changes committed during componentDidMount
hook thus preventing unnecessary cluttering of the data.
At the unmounting stage, the component gets deleted and cleared out of the page. The only lifecycle hook at this stage is componentWillUnmount
, which is called just before the component gets deleted. This is used to clear out any stuff set up in componentDidMount
. This is especially useful when during the update stage the data continuously re-renders, for instance, when setInterval
method is used. It can now use clearInterval
method to negate the results of constant re-rendering.
incrementTime = () => {
this.setState(prevState => ({
time: prevState.time + 1
}));
};componentDidMount () {
this.interval = setInterval(this.incrementTime, 1000)
}
componentWillUnmount () {
clearInterval(this.interval)
}
Conslusion
Three main cycles are answering for the three main parts of user interaction of the website, when the page loads, when it changes, and, finally, when it shuts down. These create, update, and delete methods are meant to provide the best user experience by shortening loading times and organizing the functions in a timely manner, extracting most of the Components’ performance.