facebookexperimental / Recoil

Recoil is an experimental state management library for React apps. It provides several capabilities that are difficult to achieve with React alone, while being compatible with the newest features of React.
https://recoiljs.org/
MIT License
19.59k stars 1.18k forks source link

Error: This component must be used inside a <RecoilRoot> component - React 18 #1802

Open ojoven opened 2 years ago

ojoven commented 2 years ago

I'm getting an error when trying to use Recoil on a freshly installed NextJS using React 18.

The error I'm getting is the following:

Unhandled Runtime Error
Error: This component must be used inside a <RecoilRoot> component.

when trying to use useRecoilState, like the following in a component called Star.tsx: const [activeStar, setActiveStar] = useRecoilState(activeStarState);

Of course, I'm wrapping the app inside tags, on _app.tsx:

import type { AppProps } from 'next/app';
import { RecoilRoot } from 'recoil';

import '@/styles/globals.scss';

function MyApp({ Component, pageProps }: AppProps) {
    return (
        <RecoilRoot>
            <Component {...pageProps} />
        </RecoilRoot>
    );
}

export default MyApp;

I installed a NextJs with Recoil template (https://github.com/vercel/next.js/tree/canary/examples/with-recoil) and it worked OK but they're using React 17, these being the dependencies:

"dependencies": {
    "next": "latest",
    "react": "^17.0.2",
    "react-dom": "^17.0.2",
    "recoil": "0.0.7"
  }

In the version that is not working to me (fresh install of NextJS + yarn add recoil) these are the versions:

  "dependencies": {
    "next": "12.1.6",
    "react": "18.1.0",
    "react-dom": "18.1.0",
    "recoil": "^0.7.3-alpha.2",
  }

I tried to find a similar problem here in the Issues but couldn't find anything.

Can this happen to be a problem with the versions?

Thanks

JesperKihlberg commented 2 years ago

Hi, It is hard to determine based on the code you posted, but if you have nested react roots, you can use this: https://recoiljs.org/docs/api-reference/core/useRecoilBridgeAcrossReactRoots/

ojoven commented 2 years ago

I'm not using nested react roots, but thanks for the hint!

I'll try to replicate this with the simplest example so this is easily reproducible.

PrinceKAlgorithmXpert commented 2 years ago

@ojoven You didn't find out the solution yet? I have the same error.

kevflynn commented 2 years ago

i just got the same error when trying to update from 0.7.2 to 0.7.4. Went back to 0.7.2 and the error went away

sweethuman commented 2 years ago

Hi, It is hard to determine based on the code you posted, but if you have nested react roots, you can use this: recoiljs.org/docs/api-reference/core/useRecoilBridgeAcrossReactRoots

For me this helped a lot. In my case I dynamically load a component that can only be used on client side and it's a konva canvas, and inside a stage I couldn't otherwise have access to the recoil root.