question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Wait for Nextjs rehydration before zustand store rehydration

See original GitHub issue

Hello, I’m using the persist middleware on my store with Nextjs (SSG) and I got several warnings in dev mode all pointing: Error: Hydration failed because the initial UI does not match what was rendered on the server. It doesn’t break the app however.

Looks like the zustand store rehydrates before Nextjs has finished its rehydration process. Is there a way trigger the rehydration of the zustand store after Nextjs’ rehydration process or are there better ways of handling this?

Issue Analytics

  • State:closed
  • Created a year ago
  • Reactions:8
  • Comments:13 (2 by maintainers)

github_iconTop GitHub Comments

6reactions
pixelasscommented, May 30, 2022

None of the options above or from the linked issues worked for us. The only way for us to remove the warning without checking if the component was mounted (e.g. useHasHydrated via a custom useEffect), was to trick Zustand into skipping the initial render-cycle before getting the store from window.localStorage.

@AnatoleLucet If you are sure that your solution works, it would be nice if you could provide an MVP Sandbox.

I will provide a few Sandboxes with all solutions we’ve tested tomorrow, to allow better reproduction and show that my “workaround” works (while not optimal).

This is the solution that works as a workaround for us:

const useStore = create(
  persist(
    (set) => ({
      counter: 0,
      setCounter(counter) {
        set({ counter });
      },
    }),
    {
      name: "next-zustand",
      getStorage: () => ({
        setItem: (...args) => window.localStorage.setItem(...args),
        removeItem: (...args) => window.localStorage.removeItem(...args),
        getItem: async (...args) =>
          new Promise((resolve) => {
            if (typeof window === "undefined") {
              resolve(null);
            } else {
              setTimeout(() => {
                resolve(window.localStorage.getItem(...args));
              }, 0);
            }
          }),
      }),
    }
  )
);

The trick was to add a setTimeout inside getItem. A simple promise (or async function) still wouldn’t fix the issue.

Looks ugly, feels ugly… let’s face it: “It’s ugly”

getItem: async (key) =>
  new Promise((resolve) => {
    setTimeout(() => {
       if (typeof window === "undefined") {
        resolve(null);
      } else {
        setTimeout(() => {
          resolve(window.localStorage.getItem(...args));
        }, 0);
     }
  }),
}),

Side-node: This issue started with React v18 since they seem to handle or warn about hydration different. This might be part of Next.js v12 or React.js v18, We are currently unsure about this.

The only “other” option that worked for us was to not render until the component was mounted on the client but that means either of the following caveats

3reactions
MoustaphaDevcommented, Apr 26, 2022

Thanks for the fast reply. It is in fact persist only issue.

Read more comments on GitHub >

github_iconTop Results From Across the Web

NextJS Zustand persist state - Stack Overflow
This error is caused by zustand fetching data from persist middleware storage and updating its store before NextJS hydration complete in the ...
Read more >
react-hydration-error - Next.js
When css-in-js libraries are not set up for pre-rendering (SSR/SSG) it will often lead to a hydration mismatch. In general this means the...
Read more >
Managing persistent States in Nextjs with Zustand - Dev Genius
If you are building even the smaller web app, it will happen that you will need to store some kind of data and...
Read more >
How to solve Next.js window is not defined
Solve a the common ReferenceError: next.js window is not defined error ... When a user visits the page, it will load the HTML...
Read more >
Managing React state with Zustand - LogRocket Blog
Using Zustand to persist state ; persist that persists your store in any way you want. The only thing you need to do...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found