Im trying to pass and update a state with useContext;
App.js
import Home from './components/Home'
const UserContext = createContext();
function App() {
const [name, setName] = useState('Name');
return (
<UserContext.Provider value={{name, setName}}>
<Home/>
</UserContext.Provider>
);
}
export default App;
Home.js
import UserContext from '../../App'
function Home() {
const user = useContext(UserContext);
return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}
export default Home;
Im getting this error
TypeError: Cannot read properties of undefined (reading 'name');
How is the correct way to pass state between components with useContext?
You need to export your UserContext, so it can be imported in the components that need it:
export const UserContext = React.createContext();
function App() {
const [name, setName] = useState('Name');
return (
<UserContext.Provider value={{ name, setName }}>
<Home />
</UserContext.Provider>
);
}
Afterwards you can import it in your App component:
import { UserContext } '../../App'
function Home() {
const user = useContext(UserContext);
return (
<>
<label>Your name:</label>
<input type='text' onChange={e => user.setName(e.target.value)} />
<p>{user.name}</p>
</>
)
}
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