pmndrs / zustand

🐻 Bear necessities for state management in React
https://zustand-demo.pmnd.rs/
MIT License
47.38k stars 1.46k forks source link

Zustand breaks with NextJS 13 when enabling appDir (Cannot read properties of null (reading 'useDebugValue')) #1395

Closed lucasmerlin closed 1 year ago

lucasmerlin commented 1 year ago

I created a minimal reproduction here: https://stackblitz.com/edit/nextjs-egfcaj?file=package.json

It throws the following error:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
TypeError: Cannot read properties of null (reading 'useDebugValue')
    at Module.useDebugValue (/home/projects/nextjs-egfcaj/node_modules/react/cjs/react.development.js:1659:23)
    at useStore (file:///home/projects/nextjs-egfcaj/node_modules/zustand/esm/index.mjs:37:10)
    at useBoundStore (file:///home/projects/nextjs-egfcaj/node_modules/zustand/esm/index.mjs:42:51)
    at __WEBPACK_DEFAULT_EXPORT__ (webpack-internal:///./pages/index.js:20:19)

If you remove the "appDir: true" line from next.config.js, the counter works as expected. The weirdest thing is that the project doesn't even use the app dir, just enabling the flag is enough for the error to happen. After a bit of debugging in my project, comparing the useDebugValue that is imported by zustand and the one I imported in my component, they are not equal. Seems like the multiple react copies error, although there is only one react version installed.

I also tried zustand version 3, it throws a similar error, but with the useReducer hook instead of useDebugValue. I also tried the version from here: https://github.com/pmndrs/zustand/issues/1392 but it didn't help.

Relevant NextJS discussion: https://github.com/vercel/next.js/discussions/41236

Sec-ant commented 1 year ago

Does anyone like me think this might have something to do with the "Dual Package Hazard" caused by multiple instances of a same dependency?

The reason that state is an issue is because both the CommonJS and ES module versions of the package might get used within an application; for example, the user's application code could import the ES module version while a dependency requires the CommonJS version. If that were to occur, two copies of the package would be loaded in memory and therefore two separate states would be present. This would likely cause hard-to-troubleshoot bugs.

dai-shi commented 1 year ago

Zustand library itself shouldn't suffer from Dual Package Hazard, because it doesn't have module state. (On the other hand, Jotai and Valtio have module state, so they can suffer.)

Sec-ant commented 1 year ago

@dai-shi yeah you're right it is not caused by zustand library itself. I did some test and I saw this error is triggered when useDebugValue is called on the server side. This simple patch will make the code work. Not sure about the proper way to fix this though:

diff --git a/node_modules/zustand/esm/index.mjs b/node_modules/zustand/esm/index.mjs
index 2c76b55..73ad140 100644
--- a/node_modules/zustand/esm/index.mjs
+++ b/node_modules/zustand/esm/index.mjs
@@ -13,7 +13,9 @@ function useStore(api, selector = api.getState, equalityFn) {
     selector,
     equalityFn
   );
-  useDebugValue(slice);
+  if (typeof window !== "undefined") {
+    useDebugValue(slice);
+  }
   return slice;
 }
 const createImpl = (createState) => {
dai-shi commented 1 year ago

Ah, maybe because React doesn't provide ESM. Can you try this?

// ./node_modules/zustand/esm/index.mjs
import React from 'react'

// ...
  React.useDebugValue(slice)
Sec-ant commented 1 year ago

Ah, maybe because React doesn't provide ESM. Can you try this?

// ./node_modules/zustand/esm/index.mjs
import React from 'react'

// ...
  React.useDebugValue(slice)

nope, this won't work, same error.

Sec-ant commented 1 year ago

These two issues might be relevant? (but neither solves this problem) https://github.com/vercel/next.js/issues/41929 https://github.com/react-bootstrap/react-bootstrap/issues/6475 and this doc: https://beta.nextjs.org/docs/rendering/server-and-client-components

Sec-ant commented 1 year ago

I start thinking that this issue may be a misuse of the nextjs 13 appDir feature? If I follow the docs to setup/migrate the app to nextjs 13. Everything just works: https://stackblitz.com/edit/nextjs-od7fky?file=app/Button.jsx Maybe we shouldn't keep the appDir true while using the pages dir?

dai-shi commented 1 year ago

https://github.com/pmndrs/jotai/issues/1529#issuecomment-1302156604

alizaeda commented 1 year ago

Same issue without appDir is enabled

jescalan commented 1 year ago

Hi everyone! Just want to note that we're looking into this on the nextjs team.

TomBeckett commented 1 year ago

@jescalan Good news! Anywhere we can track progress of the investigation?

jescalan commented 1 year ago

No, it's generally in our company slack. We will have something out for this soon though, it's an active priority. The core issue is the ESM thing mentioned above, which is also causing bugs with a number of other things.

btran946 commented 1 year ago

@jescalan any suggestions on state management tools similar to Zustand in the mean time?

nhatimme commented 1 year ago

We also facing a issue when we want to load the store into a file which is located at /app/contact.tsx (It gives an error like: Unhandled Runtime Error Error: useRef is not a function )

contact.tsx

import useBearStore from '../../stores/cart'

function HomePage() {
  const { bears } = useBearStore();
  return (
    <main>
      Contact
      { bears }
    </main>
  )
}

export default HomePage;
adriannecris commented 1 year ago

We also facing a issue when we want to load the store into a file which is located at /app/contact.tsx (It gives an error like: Unhandled Runtime Error Error: useRef is not a function)

contact.tsx

import useBearStore from '../../stores/cart'

function HomePage() {
  const { bears } = useBearStore();
  return (
    <main>
      Contact
      { bears }
    </main>
  )
}

export default HomePage;

@nhatimme Have you tried adding 'use client'; at the very first line. Reference in this link

nhatimme commented 1 year ago

@adriannecris Thanks. So it is impossible to use it as Server Side component?

jescalan commented 1 year ago

Yeah, it's never going to be possible to use zustand in a server component, as state is not supported by server components in general. It works quite well in app directory right now as long as you are using client components. Actually I think it may be working fine with the latest version of nextjs, I just made a reproduction repo here and everything is working quite nicely. This includes an example of it working both in pages and app directory.

Let me know if I missed anything or if anyone has a reproduction with the latest version - hopefully this can be closed out!

Edit: confirmed that updating to 13.0.3 in the original stackblitz fixes the issue

nhatimme commented 1 year ago

@jescalan: Perfect.

rumrum28 commented 1 year ago

still having this issue im 13.0.6 now

vlausargs commented 1 year ago

can use it just fine after add "use client"

wootra commented 1 year ago

@adriannecris Thanks. So it is impossible to use it as Server Side component?

you may be able to use useBearStore.setState(...) / useBearStore.getState().myVal in the server side without an issue.

wootra commented 1 year ago

all client based hook should be used after adding 'use client' on top of the file. But Next13 does not give a good error message where is missing. That is really tough since I have to find it manually.

Scdales commented 1 year ago

can use it just fine after add "use client"

@vlausargs Which files are you labelling 'use client'? I have tried adding it to all files that import anything from zustand and I'm still seeing the error appearing:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
TypeError: Cannot read properties of null (reading 'useDebugValue')
wootra commented 1 year ago

can use it just fine after add "use client"

@vlausargs Which files are you labelling 'use client'? I have tried adding it to all files that import anything from zustand and I'm still seeing the error appearing:

Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
TypeError: Cannot read properties of null (reading 'useDebugValue')

it could be because of a lot of reason and next 13 sometimes gives not even relative error. worst part is it ia hard to tell where is the origin of the error.. you might want to move all page and app path to somewhere else not in the app directory to narrow down where is the origin of the issue. but some of cases you may check to figure out where is it coming from, tty below.. not 100% sure though. make sure if you wrap the component that uses "use client" as a separated component to use it in the server component. you may be using "use client" in the page.jsx file. async component cannot be used with client component. you may call hook after returning content. you shouldnt use hook in the server or async component.

kcrwfrd commented 1 year ago

We encountered this error when using Next.js 13.4 with a custom server, even though we were not using the new app dir. I believe the problem is explained here: https://github.com/vercel/next.js/issues/49355#issuecomment-1537536063

We've fixed this for now by specifying our Next.js version as ~13.3.4

sushantdhiman commented 1 year ago

It seems like this issue is fixed with next@13.4.3 for custom server (my use case). This issue is tracked in Next.js https://github.com/vercel/next.js/issues/49355, it is not related to just zustand. I think this issue should be closed.

coder-abdo commented 1 year ago

it is working fine when I tried it you can see it below example: https://codesandbox.io/p/sandbox/cocky-mcclintock-38j52j?file=%2Fapp%2Fpage.tsx%3A13%2C28

ocodista commented 1 year ago

I think this issue should be closed.

lucasmerlin commented 1 year ago

Zustand has been working fine in my nextjs project with app dir, so I'm closing this issue now.

adarshaacharya commented 1 year ago

still getting same error, on pages directory. Using following version of next and zustand:

    "next": "13.4.19",
    "zustand": "^4.4.1"
Emiliano-Bucci commented 1 year ago

Issue seems to appear again with next 13.4.19

hazzo commented 1 year ago

still getting same error, on pages directory. Using following version of next and zustand:

    "next": "13.4.19",
    "zustand": "^4.4.1"

Did you try deleting .next folder?

OlegLustenko commented 12 months ago

It started reproducing again in Next v14, pages dir in the Docker. App dir is fine.

I've tried ppr: true won't help image

Zustand version is 4.4.4

dai-shi commented 12 months ago

Please try #2154 https://ci.codesandbox.io/status/pmndrs/zustand/pr/2154 ☝️ Find "Local Install Instructions"

OlegLustenko commented 12 months ago

it was fast! Thanks!

JanRuettinger commented 11 months ago

Issue not fixed yet it seems. I face the issue with "next": "13.4.19", "zustand": "^4.4.1" and page dir.

OlegLustenko commented 11 months ago

@JanRuettinger update Zustand to the latest version

AnimeshTimsina commented 10 months ago

This issue appears again on "next": "14.0.3", "zustand": "^4.4.7"

SysWhiteDev commented 9 months ago

Issue is here again on "next": "14.1.0", "zustand": "^4.5.0"