How to Use React Recoil with Gluestack

122 Views Asked by At

I am learning to create an app with the Gluestack UI. I want to use Recoil for state management. However, at this time, I'm receiving the following error:

Uncaught TypeError: Cannot read properties of null (reading 'useContext')

My code looks like this:

state.js

import { atom } from 'recoil';

export const appStateAtom = atom({
    key: 'ApplicationState',   
    default: {
        name: 'My Application'
    }
});

App.tsx

import { Box, GluestackUIProvider, Text } from '@gluestack-ui/themed';
import { ScrollView } from 'react-native';
import { RecoilRoot, useRecoilState } from 'recoil';
    
import { appStateAtom } from './state.js';
const [appState, setAppState] = useRecoilState(appStateAtom);

export default function App() {
  return (
    <RecoilRoot>
      <GluestackUIProvider>
        <Home />
      </GluestackUIProvider>
    </RecoilRoot>    
  );
}

const Home = () => {
  return <Container />;
};

const Container = () => {
  return (
    <Box flex={1} backgroundColor="$black">
      <ScrollView
        style={{ height: '100%' }}
        contentContainerStyle={{ flexGrow: 1 }}
      >
        <Box
          height="60%"
          sx={{
            '@base': {
              my: '$16',
              mx: '$5',
              height: '80%',
            },
            '@lg': {
              my: '$24',
              mx: '$32',
            },
          }}
          justifyContent="space-between"
          alignItems="center"
        >
          <Text color="$white" fontWeight="$medium" ml="$2">Hello</Text>
        </Box>
      </ScrollView>
    </Box>
  );
};

I do not understand why I am getting the error shown above. The error goes away when I comment out the line with const [appState, setAppState] = useRecoilState(appStateAtom);. That doesn't make sense to me though. What am I doing wrong? How do I include Recoil in my Gluestack app.

1

There are 1 best solutions below

0
Dev On

I figured out the issue. The issue is that I was calling useRecoilState in the same component that I was setting up the RecoilRoot. The useRecoilState method can only be used in a component that is a descendant of RecoilRoot.