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.
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.
...
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 (...)
}
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.
...
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.
If you want to persist the value through page navigation or refreshes, you'll likely need to store the profile value in something that's persisted and load the value from the data store to the context. You can use something like a db or possibly local storage. On app load, you'll make the API call to retrieve these values and store it in your context.