React useEffect only Once - Robin Wieruch

React useEffect only Once - Robin Wieruch

If you are wondering how to run React’s useEffect Hook only once , 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 once (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 once, however, this custom hook should help you to accomplish it. Let me know if this helps you.

Recommended articles