Reputation: 5
I needed to access window.localStorage
in my Next.js app but since Next.js allows both server-side and client-side rendering, when i tried to set the default value of a state using the local storage like this:
useState(window.localStorage.getItem("tag"))
it would throw an error saying window
was undefined.
In order to find a way to make it work, i used a useEffect and set the value of the state once the component fully rendered, like this:
useEffect(() => {
setState(localStorage.getItem("tag"));
}, []);
But i am not sure if this was the right approach. Is this a good solution or is there a better way? Thanks.
Upvotes: 0
Views: 2703
Reputation: 7661
This is correct.
Due to hydration, when the component is created at the backend, it doesn't have access to window
object. And seems to me useEffect
isn't run at the backend. I guess backend only assembles the first frame (mount) render.
Thus useEffect
is the way to dodge this issue. Of course people can also check whether window
exists, but I feel useEffect
is more elegant.
Upvotes: 0