Hey there, hopefully, you've read the first part of the series and if not go and read.
So, now we're discussing ** Update lifecycle hooks on props and state change.**
So, let's point out in what ways you can update a component,
- Change state
- Change prop
So react provides several hooks which can be accessed to handle these changes, so we're going to discuss each of them one by one.
-
getDerivedStateFromProps, as discussed in Part-1, this hook runs in both mounting and updating cycle, and it takes
props and state
as the arguments so the developer can update state according to change in props and most importantly it should return an object to update the state, or null to update nothing also make sure not to doside-effects
here.
static getDerviedStateFromProps(props,state) {
//update the state if required
return state //or null
}
-
shouldComponentUpdate, so here is a great hook that we can utilise to improve performance of our application, let's say we props get updated but we don't want to re-render the component for some reasons, so here we can utilise this hook and return a boolean
true to continue updating, false to abort
, this way we can reduce unnecessary re-rendering thus improving performance. Also, don't doside-effects
here.
Also, interesting takeaway, the nextState
comes from the getDerviedStateFromProps
method.
shouldComponentUpdate(nextProps, nextState) {
if(/*Some checks*/) {
return true
}
return false
}
- render, as we discussed we know what we're gonna do here Prepare your JSX.
render() {
return <div>I love React</div>
}
Update child components, nothing here.
getSnapshotBeforeUpdate, this is an interesting hook, here we get last-minute snapshot of the component before the update, which means previous props and state which are passed as arguments in it so that we can do some computation if required. A snapshot value (or null) should be returned.
The best use case is we can use it to store user position in an application, so after the update, we can scroll it to that position automatically hence improving user experience.
Still not a goot place for side effects.
getSnapshotBeforeUpdate(prevProps, prevState) {
// Code here
}
- componentDidUpdate, reaching the end, this is the best time for side-effects because our application is updated and we do anything we want. Protip: Try to keep side-effects async, so it won't mess up with react lifecycle. Also, don't update the state here, it'll cause re-render.
componentDidUpdate(prevProps, prevState, snapshot) {
}
What about when the component unmounts or get destroyed?
Here we can use componentWillUnmount
, this will be executed just before the component is unmounted and this is best for cleanup work,don't update state here cause it'll never be re-render.
Here it is the end of part 2, hope you enjoyed it! I'm extremely tired so will write part 3 later. Anyway happy coding! Please like and follow <3 it'll motivate me.
Top comments (1)
I value the insights and guidance you provided.