componentDidUpdate() alternative in React hooks
If you’ve been working with functional components in React from the very start you may not be able to realize the importance of this hook but the people coming from class based components can understand the importance of this hook. (P.S. I despise class based components in React xD)
Prerequisites
Good understanding of the following hooks:
- useRef()
- useEffect()
If you want to just know how to implement this go ahead and skip this next section and jump to the solution section.
So why is this required ?
Just consider a situation where you wanted to change the state of a variable not on the first render of the component but on every next render (on update).
Get Akshit’s stories in your inbox
Join Medium for free to get updates from this writer.
In the case below the alert gets popped on the first render as well.
Solution :
You can implement the componentDidUpdate using hooks as follows.
In the above code the didMountRef acts as stateless boolean variable storing the information if the component is being mounted for the first time or being rendered again.
The doStuff() function can be replaced by any piece of code you want to do on component update.
Consider sharing this article with your friends and co-developers if you found this article useful. Stay Curious!


