zustand icon indicating copy to clipboard operation
zustand copied to clipboard

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

Open lucasmerlin opened this issue 2 years ago • 20 comments

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

lucasmerlin avatar Oct 27 '22 23:10 lucasmerlin

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.

Sec-ant avatar Nov 01 '22 18:11 Sec-ant

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.)

dai-shi avatar Nov 01 '22 23:11 dai-shi

@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) => {

Sec-ant avatar Nov 02 '22 04:11 Sec-ant

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)

dai-shi avatar Nov 02 '22 04:11 dai-shi

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 avatar Nov 02 '22 04:11 Sec-ant

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 avatar Nov 02 '22 06:11 Sec-ant

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?

Sec-ant avatar Nov 02 '22 06:11 Sec-ant

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

dai-shi avatar Nov 03 '22 14:11 dai-shi

Same issue without appDir is enabled

alizaeda avatar Nov 03 '22 14:11 alizaeda

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

jescalan avatar Nov 09 '22 22:11 jescalan

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

TomBeckett avatar Nov 11 '22 11:11 TomBeckett

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.

jescalan avatar Nov 11 '22 22:11 jescalan

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

btran946 avatar Nov 12 '22 22:11 btran946

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 avatar Nov 15 '22 11:11 nhatimme

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

adriannecris avatar Nov 15 '22 12:11 adriannecris

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

nhatimme avatar Nov 15 '22 12:11 nhatimme

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

jescalan avatar Nov 18 '22 01:11 jescalan

@jescalan: Perfect.

nhatimme avatar Nov 18 '22 12:11 nhatimme

still having this issue im 13.0.6 now

rumrum28 avatar Dec 06 '22 02:12 rumrum28

can use it just fine after add "use client"

vlausargs avatar Dec 11 '22 02:12 vlausargs

@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 avatar Feb 03 '23 18:02 wootra

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.

wootra avatar Feb 03 '23 18:02 wootra

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')

Scdales avatar Mar 01 '23 18:03 Scdales

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.

wootra avatar Mar 05 '23 05:03 wootra

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

kcrwfrd avatar May 17 '23 20:05 kcrwfrd

It seems like this issue is fixed with [email protected] 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.

sushantdhiman avatar May 23 '23 05:05 sushantdhiman

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

coder-abdo avatar Jul 22 '23 10:07 coder-abdo

I think this issue should be closed.

ocodista avatar Jul 30 '23 16:07 ocodista

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

lucasmerlin avatar Jul 30 '23 17:07 lucasmerlin

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

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

adarshaacharya avatar Sep 04 '23 14:09 adarshaacharya