Component LifeCycle methods
Lifecycle methods in React (Class-based Components)
3 min read
In react, every component goes through a process called component lifecycle. This component lifecycle explains the interactivity of data to UI on the page.
- So, first, a Component will mount and the constructor() where the class instance gets created and the state gets instantiated. And it renders, basically put UI to the page.
- And whenever setState() gets called or new props are received, it needs to re-render, it will update UI. This part of the lifecycle updates and re-renders with some lifecycle methods.
- And when there comes time for a component to disappear or when you need to clear something that you created in the mount stage, it is removed in Unmount stage.
You can follow this diagram to visualize the lifecycle of a component.
Let's see what it means in Practice
Use Slider to see the code
- initialize state or other class properties (e.g , bound methods)
- the meat of a component
- return a node
- Do anything that isn't needed for UI (async actions, timers, etc.)
- setting state here will cause a re-render before updating the UI
Just like in the Mounting cycle, a bunch of lifecycle hooks are called in the update cycle, every single time we want to re-render.
- update any state fields that rely on props. -shouldComponentUpdate(nextProps, nextState)
- compare changed values,before rendering. return true id the component should re-render
- if returned false, update cycle will terminate.
- Almost always a premature condition.
- componentDidUpdate(prevProps, prevState)
- Do anything that isn't needed for UI (network requests, api call etc).
In update cycle, firstly shouldComponentUpdate() is invoked, then render() and only then componentDidUpdate().
This is an important stage of the component lifecycle. It is where cleanup is performed after the component is unmounted. The reason to clean up after unmounting any timers, background calls is to optimize the application for the user's intended experience. An application must compute the result with full memory usage designated to the task at hand, not lag due to past actions. Pending requests must get eliminated as soon as the interaction with the specific component is over.
If we do not unmount the component, background calls, functioning will keep on running and stacking up the memory. See thi example. Check the console and press the toggle button. %
To solve the problem we must register an unmount stage after the use of the component is done. As it will clear the space and will optimize the whole application
- clean up ~ Remove event Listeners ~ Invalidate Network Requests ~ Clear timeouts/intervals
Error Handling: Here You can continue learning about lifecycle hooks for functional Component
Did you find this article valuable?
Support Agrit Tiwari by becoming a sponsor. Any amount is appreciated!