LocalStorage and useEffect
In a typical CRUD scenario, one would be using the above mentioned like this:
• useEffect => On load: check if localStorage data exists, then parse it and save in state.
• useEffect => Listens for changes in state data, then saves it to localStorage.
How can I prevent the second
useEffect
from running after the first on initial load?
Let's say I have already added some data in localStorage. When my app loads, it fetches said data and calls setState
to save it in my local state. Since this data is in the dependency array of the second useEffect
, it triggers it, saving nothing.
Thanks!2 Replies
can you show code?
One very dirty trick would be to initialize the state with the local storage value.
However, like I said, it's very dirty, because the local storage operation is actually synchronous, but behaves like it's asynchronous, so it might not work well sometimes.
Second option, which is cleaner, would be to use a
No Initial Render Effect
method (trick) to check if it's the first render on the second useEffect. If it is, don't update localStorage, if it isn't, update localStorage.