anoop chandran
anoop chandran

Reputation: 1500

How to provide and consume context in the same component?

I'm using react context api for my game app and I created a GameContext.js

import React, { useState, createContext } from 'react';

const GameContext = createContext();
const GameProvider = ({ children }) => {
  const [startgame, setStartgame] = useState(false);

  return (
    <GameContext.Provider value={[startgame, setStartgame]}>
      {children}
    </GameContext.Provider>
  );
};

export { GameContext, GameProvider };

And in the App.js I provide the context.

import { GameProvider, GameContext } from './context/GameContext';

const App = () => {
    console.log(useContext(GameContext), 'Gamecontext');
    return (
      <GameProvider>

        <div className="App">
            {!startgame ? <WelcomeScreen />
        : <GameScreen />}
        </div>
      </GameProvider>
    );
  };
  export default App;

This doesnt work because startgame is not accessible in App.js.
Also, I noticed the useContext(GameContext) is undefined. I want to use the startgame value in App.js, but I cant destructure an undefined value. How can one provide and consume the context in the same component App.js? Is this the right way or am missing something?

Upvotes: 2

Views: 2960

Answers (1)

TheMisir
TheMisir

Reputation: 4279

You need to use Context.Consumer component instead of useContext hook. Because when you provide a context, it will be consumable via useContext hook or this.context only within its children not parent. In that case you need to use MyContext.Consumer component.

import { GameProvider, GameContext } from './context/GameContext';

const App = () => {
  return (
    <GameProvider>
      <div className="App">
        <GameContext.Consumer>
          {(ctx) => (!ctx.startgame ? <WelcomeScreen /> : <GameScreen />)}
        </GameContext.Consumer>
      </div>
    </GameProvider>
  );
};

export default App;

From React docs:

Consumer - Requires a function as a child. The function receives the current context value and returns a React node. The value argument passed to the function will be equal to the value prop of the closest Provider for this context above in the tree. If there is no Provider for this context above, the value argument will be equal to the defaultValue that was passed to createContext().

Upvotes: 12

Related Questions