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?