Intro to React Lifecycle Methods
The idea of the React lifecycle is that a component has mainly 3 different parts.
- Mounting — In this phase, the component is created and inserted into the DOM
- Updating — The component changes by receiving new updates
- Unmounting — The component is no longer needed and gets unmounted
Part 1 — Mounting
There are a few methods that called on when the instance of a component is being created and inserted into the DOM:
//used to initialize state and bind event handler methods.
constructor()//returns an object containing the updated state. Allows a component //to update its internal state in a response to a change in props.
getDerivedStateFromProps()//must return a JSX element to render.
render()//called after render() and after component is mounted to the DOM.
Part 2— Updating
Whenever there are changes inside the component or parent component then the component may need to be re-rendered, like if the state or props got changed. This requires the methods below to be invoked for a component being updated.
//this is the first method invoked in a response to change in props.
getDerivedStateFromProps()//this method will decide if a component will update or not.
shoudlComponentUpdate()//render is called.
render()//this method gets called bfore the render and can help capture info //about the DOM.
Part 3 — Unmounting
After the updates are completed, the next step is to move into the unmounting phase where the methods below will be valid.
//this is invoked before a component is unmounted and destroyed and //can be used as a way to clean things up.
I hope this gives a little more insight into what happens during the React lifecycle and what methods are invoked. One of the easiest ways to understand the lifecycle is to break it into parts and to make sure you’re using the right methods in the specific parts.