When I use React.useEffect hook with empty dependency array, it re-renders on every re-routing when the back button pressed, not only once. Is there a minimal solution for a function to execute only once inside the whole app?
Question posted in Javascript
A very good W3school tutorial can be found here.
A very good W3school tutorial can be found here.
3
Answers
When the component mounts it will run it. If you unmount the component and re mount the component, it will render again. Move the useEffect to something that is above your router and it will only render once.
One possible solution to ensure a function is run only once throughout the entire app is to leverage the capabilities of local storage. By storing a flag that indicates whether the function has been previously executed, the app can check for this flag each time it is loaded and execute the function only if the flag is not present.
you can also change it as sessionStorage instead of localStorage to only run once per user session.
creating a custom hook that takes a function as an argument and only executes it once. would be reusable and can be called in any component, passing in the desired function as an argument.
Using the hook in component:
will only be executed once, and the hook can be reused in other components as well.