I'm creating a react game app and I want to pass state across multiple components. For that purpose I'm trying the react context api for the first time. So this is my GameContext.js
import React, { useState, createContext } from 'react';
const GameContext = createContext();
const GameProvider = ({ children }) => {
const [name, setName] = useState('');
const [color, setColor] = useState('');
const [startgame, setStartgame] = useState(false);
return (
<GameContext.Provider value={[name, setName]}>
{children}
</GameContext.Provider>
);
};
export { GameContext, GameProvider };
And I'm able to access name in the child component using
import { GameContext } from '../../context/GameContext';
const [name, setName] = useContext(GameContext);
console.log(name);
But now I want to get the other state values into the same child component, like [color, setColor] and [startgame, setStartgame], from the GameContext.js.
How do I get those values into a child component?
I have another question, Somehow I feel this is a really stupid question, but why can't I do something like this in the GameContext.js?...
<GameContext.Provider value={[name, setName,color, setColor, startgame, setStartgame]}>
and get the values in the child component like this...
const [name, setName,color, setColor, startgame, setStartgame] = useContext(GameContext);
I tried this, but the browser is complaining that I'm breaking rules of react hooks.