Next.js Discord

Discord Forum

Hydration Error with Local Storage

Answered
Leonberger posted this in #help-forum
Open in Discord
LeonbergerOP
I'm creating a recent searches feature for a restaurant app, for that I've created a custom hook "useLocalStorageSearches" and on click of a searched restaurant it calls "addToRecentSearches" function which updates the recentSearches, but for some reason I'm facing Hydration Error.
Answered by Rafael Almeida
the return of the callback function of useState has to be the same on the server and the client for the first execution. since you are using a conditional with typeof window then it will always be different, resulting in the hydration error

you need to initialize the state with an empty value then read from localStorage using useEffect or useSyncExternalStore
View full answer

3 Replies

@Leonberger I'm creating a recent searches feature for a restaurant app, for that I've created a custom hook "useLocalStorageSearches" and on click of a searched restaurant it calls "addToRecentSearches" function which updates the recentSearches, but for some reason I'm facing Hydration Error.
the return of the callback function of useState has to be the same on the server and the client for the first execution. since you are using a conditional with typeof window then it will always be different, resulting in the hydration error

you need to initialize the state with an empty value then read from localStorage using useEffect or useSyncExternalStore
Answer
LeonbergerOP
Oh yes, now I'm using another usEffect to get Items from localStorage and setting the useState to inital value which is [], but it is getting re-rendered and again setting the localStorage back to [] and I can't seem to find a way around can you help me with that?