useContext across files causes circular dependencies

Viewed 1941

I have a two components Parent and Child and I want to export a context from Parent to Child but this causes circular dependency.

Consider, for example, Parent.js to be

import {Child} from './Child.js';

export const MyContext = React.createContext();

const Parent = () => {
    return <MyContext.Provider><Child /></MyContext.Provider>;
}

and Child.js as

import {MyContext} from 'Parent';

const Child = () => {
    const myContext = useContext(MyContext);
    return <>{myContext}</>;
}

I can pass this as props but if there are multiple level of nesting, it would be difficult. A possible solution I can think of is using another file called contexts.js and have all my contexts exported from there.

Is there a better way to do this?

2 Answers

Put your context in it's own file, .e.g Context.js. Then both Parent.js and Child.js can import it.

Typically, rather than making the child a dependency of the parent, you loosely couple your context provider component from its children by making use of props.children.

Parent.js:

export const MyContext = React.createContext();

const Parent = ({ children }) => {
    return <MyContext.Provider>{children}</MyContext.Provider>;
};

export default Parent;

Child.js:

import { MyContext } from './Parent';

const Child = () => {
    const myContext = useContext(MyContext);
    return <>{myContext}</>;
};

export default Child;

Then you populate props.children with <Child /> when you create your virtual DOM:

import Parent from './Parent';
import Child from './Child';

const App = () => {
    return <Parent><Child /></Parent>;
};

...
Related