I’m trying to store a user object inside an atom and have it be cached inside localStorage
each time it changes because the app might crash and I do not want the user to have to sign in every time:
localStorage.setItem('user', JSON.stringify(user))
Previously when I used useContext
this was achieved through a useEffect
in the parent component (App.js) that monitored the user
object for changes. It’s no longer possible for me to do this after migrating from useContext
to Recoil
due to my NextJS project structure (RecoilRoot
wraps around the children component, so the parent App.js
itself does not have access to useRecoil
methods). And so, I’m wondering if there’s a way to implement this kind of listener or callback using a built-in Recoil method
Desired process:
- Declare the state:
const [user, setUser] = useRecoilState(userAtom)
- Trigger a change
setUser({...})
- Trigger a callback on state change
localStorage.setItem('user', JSON.stringify(user))