Run function or script only once inside useEffect React

When you build a component with useEffect hook, sometime you'd like to run some functions or scripts inside only once. But you'd like to keep re-run some other function or scripts when the component updated.

Consider folowing way, may it's helpful for you in this case.

In the example above, the APIs functions and some functions that you'd like to run only once will be run when the component has updated. And what you want to be done has gone :(

So, in this case, you should break the useEffect hook for two purposes, one for run scripts that you'd like to run many times and one for the scripts run only once:

Note: In the second useEffect hook above, we must pass the second param is a empty array, this make the useEffect will be called only once in the component.

© 2019 4codev

Created with love by Sil.