React Native with Context API warnings: "Require cycles are allowed, but can result in uninitialized values... "

Viewed 3555

When I use React's Context API in my Expo React Native project get this warning:

Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle.

Im creating a context in App.tsx:

import Start from "./start";

export const AppContext = React.createContext({
  isLandscape: true,
});

export default function App() {
  return (
    <AppContext.Provider value={{ isLandscape: false }}>
      <Start />
    </AppContext.Provider>
  );
}

And in a Start.tsx component I'm using the context:

import { AppContext } from "./App"

export default function App() {
  const context = React.useContext(AppContext);
  console.log(context);

  return (
    <Text>Sutff</Text>
  );
}

I looks like the warning is because App imports Choose which then imports the context from App again. Require cycles are allowed, but can result in uninitialized values. Consider refactoring to remove the need for a cycle

However isn't this how the Context API is supposed to be used? How do people normally deal with this when using the Context API in React Native?

1 Answers

To break a cycle, move the shared context to a separate file.

// in AppContext.js

export const AppContext = React.createContext({
  isLandscape: true,
});

and then in App.js and Start.js, import context from that file.

import { AppContext } from './AppContext'

Thus, instead of having App <-> Start depend on each other, you now have App -> AppContext and Start -> AppContext, thus breaking the cycle.

Related