I am using useContext to pass the account name to all the pages that I have created in app.js.
contextProvider.jsx
import { createContext, useState } from 'react';
export const LoginContext = createContext(null);
const ContextProvider = ({children}) => {
const [ account, setAccount ] = useState('');
return (
<LoginContext.Provider value={{ account, setAccount }}>
{children}
</LoginContext.Provider>
)
}
export default ContextProvider;
Now I am using it in app.js for making it available for all pages.
app.js
import ContextProvider from './context/ContextProvider';
export default function app(){
return (
<ContextProvider>
<BrowserRouter>
<Routes>
{/* home page where i changing the account value */}
<Route exact path='/home-services' element={<HouseDeckHomeServicesMainPage city={city} setCity={setCity} handleData={handleData} />} />
<Route exact path='/home-services/about-us' element={<HouseDeckHomeServicesAnotherPage />} />
</Routes>
</BrowserRouter>
</ContextProvider>
);
}
Then I recalling the variables in LoginContext from contextProvider.jsx to change or set them to a partcular value.
Header.jsx
export default function Header(){
const {account, setAccount} = React.useContext(LoginContext)
// let I am doing in header.jsx
setAccount("hello")
return (
<div>{account}</div>
)
}
Suppose i am doing setAccount("Hello") in my Header.jsx to change it. The LoginContext variable account changed. I checked by printing it.
Now I want to use the same value that I stored in account in other pages.
I don't know how to use that value.
Right now I am doing
AnotherPage.jsx
export default function AnotherPage() {
const {account} = React.useContext(LoginContext)
// I want to print the value of account that i changed from
// null to "hello" in this page but i am getting undefined
// here.
console.log(account)
return (
<div>{account}</div>
)
}
But it is taking the default value of account that is null which is not what I want. I want to use the changed value. Please help.
CodePudding user response:
I've faced exactly your problem.
Time to use useMemo
:
const dataMemo = useMemo(() => {
return {
account, setAccount
}
}, [account, setAccount])
return <LoginContext.Provider value={dataMemo}>
{children}
</LoginContext.Provider>
Don't forget import {useMemo} from 'react'
on the top
Hope it can help ^^
CodePudding user response:
You propably dont have your Header.jsx
outside of you ContextProvider
.
Try to wrap whole App component in it instead of just routes