React useEffect only on Update - Robin Wieruch

React useEffect only on Update - Robin Wieruch

If you are wondering how to run React’s useEffect Hook only on update , you may be surprised that you need React’s useRef Hook as helper to create an instance variable for tracking the component’s lifecycle. The following code shows you how to achieve it:

If you want to have a reusable custom hook for it, which only triggers the effect function only on update (and not on mount), you can use the following hook for it:

That’s it. React’s useEffect Hook doesn’t come with a feature to run it only on update, however, this custom hook should help you to accomplish it. Let me know if this helps you.

Recommended articles