I have a React Context API in use in my NextJS web app.
I'd like to persist a value throughout the web app. I know I can use the Consumer
tag inside the Provider
tag to update the value.
Like so:
<ProfileContext.Provider>
<ProfileContext.Consumer>{... some logic ...}</ProfileContext.Consumer>
</ProfileContext.Provider>
But I'd like to use the useContext()
call to update a value by passing in a State object.
user_profile.js
import { useState } from 'react'
import { createContext, useContext } from 'react'
const ProfileContext = createContext()
export function ProfileProvider({ children }) {
const [profile, setProfile] = useState("default value")
return (
<ProfileContext.Provider value={{ profile, setProfile }}>
{children}
</ProfileContext.Provider>
)
}
export const useProfileContext = () => {
return useContext(ProfileContext)
}
The issue is the value I assign using setProfile(...)
does not retain value when I navigate to another page.
user_account.js
...
export default function UserAccount() {
const profileContext = useProfileContext()
profileContext.setProfile("SOME TEXT PROFILE VALUE")
console.log("PROFILE CONTEXT: ", profileContext.profile) // This will show previously set value
return (...)
}
_app.js
export default function App(pageProps) {
return (
<ProfileProvider>
<Component {...pageProps} />
</ProfileProvider>
)
}
When I navigate to some other page, the state will not have changed and will return null or the default value.
some_other_page.js
...
export default function Home() {
const profileContext = useProfileContext()
console.log(profileContext.profile) // "default value"
return (...)
}
My main guide was https://www.netlify.com/blog/2020/12/01/using-react-context-for-state-management-in-next.js
Most other examples I've read use the Provier-Consumer
tags to access and change the Context value.