Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass State in Context React

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?

like image 294
Sasquatch Avatar asked May 07 '26 22:05

Sasquatch


1 Answers

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>
        </>
    )
}
like image 154
Marco Avatar answered May 09 '26 11:05

Marco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!