I'm trying to use React Context to manage states for my project, but I can't seem to make it work for my CRA codebase this time while I had successful attempts on other projects. useContext
returns undefined so I couldn't access the values inside the context, but I have double checked that my Provider is at my app root level. Appreciate any help.
This is my simplified App component:
import React, { useContext } from 'react';
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom';
import './App.css';
import { PlayerContextProvider, PlayerContext } from 'contexts/PlayerContext';
const App = () => (
<PlayerContextProvider>
<Test />
<Router>
<Switch>
<Route path="/" exact component={Home} />
</Switch>
</Router>
</PlayerContextProvider>
);
const Test = () => {
const values = useContext(PlayerContext);
console.log('test values', values); // returns undefined!
return <div>Hello World</div>;
};
export default App;
This is my context:
import React, { useState, createContext } from 'react';
const PlayerContext = createContext();
const PlayerContextProvider = ({ children }) => {
const [players, setPlayers] = useState(['test']);
const addPlayer = ({ name }) => {
setPlayers([...players, { name }]);
};
const values = { players, addPlayer };
console.log('context values', players); // shows ['test'] here
return (
<PlayerContext.Provider values={values}>
<>
{players}
{children}
</>
</PlayerContext.Provider>
);
};
export { PlayerContextProvider, PlayerContext };
If useContext fails to create a context, it'll return undefined because we forgot the wrap our App or component in a ThemeProvider.
The hook returns the value of the context: value = useContext(Context) . The hook also makes sure to re-render the component when the context value changes.
Syntax: const authContext = useContext(initialValue); The useContext accepts the value provided by React. createContext and then re-render the component whenever its value changes but you can still optimize its performance by using memoization.
Understanding React “useContext” Hooks“useContext” hook is used to create common data that can be accessed throughout the component hierarchy without passing the props down manually to each level. Context defined will be available to all the child components without involving “props”.
You have a small typo.
Instead of values
the correct is value
without s
.
<PlayerContext.Provider value={values}>
If you are getting undefined
and isn't because of the typo, you probably forgot to "wrap" a component with the Provider
and the undefined
value comes from the first argument of React.createContext()
(which is undefined is you don't pass anything)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With