oemera
oemera

Reputation: 3443

Is it possible to use a context inside another context with react (hooks)?

When I have two contexts, where one is inside another one:

  ...
    <ContextOne.Provider value={valueOne}>
      <ContextTwo.Provider value={valueTwo}>
        {children}
      </ContextTwo.Provider>
    </ContextOne.Provider>
  ...

Is it possible that ContextTwo now uses ContextOne:

// ContextTwo.jsx
...
const contextOne = useContext(ContextOne);
console.log(contextOne.valueOne); // returns undefined
...

Basically, ContextOne transforms valueOne into a state (useState) and ContexTwo needs to use the state. In my case, the values of contextOne are somehow undefined, while there are no async operations at all. I thought this is possible since ContextTwo.Provider is inside ContextOne.Provider?

At this point, I don't really know if this just isn't possible or if there is something wrong with my code in general.

Upvotes: 2

Views: 1978

Answers (1)

Dennis Vash
Dennis Vash

Reputation: 53884

Yes, its possible, you need to useContext within ContextTwo wrapper, for example:

const ContextOne = createContext();
const ContextTwoInner = createContext();

const ContextTwo = ({ value, children }) => {
  const valueOne = useContext(ContextOne);
  console.log(valueOne);

  return (
    <ContextTwoInner.Provider value={value}>
      {children}
    </ContextTwoInner.Provider>
  );
};

// For OP's code to work
ContextTwo.Provider = ContextTwo;


// Logs valueOne
const App = () => {
  return (
    <ContextOne.Provider value={valueOne}>
      <ContextTwo.Provider value={valueTwo}>
        <div>Hello</div>
      </ContextTwo.Provider>
    </ContextOne.Provider>
  );
};

Edit fancy-cherry-cy3mq

Upvotes: 4

Related Questions