title | description | nav |
---|---|---|
Next.js |
How to use Jotai with Next.js |
3.04 |
Jotai has support for hydration of atoms with useHydrateAtoms
. The documentation for the hook can be seen here.
It's possible to sync Jotai with the router. You can achieve this with atomWithHash
:
const pageAtom = atomWithHash('page', 1, {
replaceState: true,
subscribe: (callback) => {
Router.events.on('routeChangeComplete', callback)
window.addEventListener('hashchange', callback)
return () => {
Router.events.off('routeChangeComplete', callback)
window.removeEventListener('hashchange', callback)
}
},
})
This way you have full control over what router event you want to subscribe to.
It's important to note that you can't return promises with SSR - However, it's possible to guard against it inside the atom definition.
If possible use useHydrateAtoms
to hydrate values from the server.
const postData = atom((get) => {
const id = get(postId)
if (isSSR || prefetchedPostData[id]) {
return prefetchedPostData[id] || EMPTY_POST_DATA
}
return fetchData(id) // returns a promise
})
Because of the nature of SSR, your app can have more instances existing in JS memory in the same time. You need to wrap your app inside a Provider
(view more details in the Core section) so that each instance has its own state and will not interfere with previous values from a default store (provider-less mode).
npx create-next-app --example with-jotai with-jotai-app
# or
yarn create next-app --example with-jotai with-jotai-app
Here's a link.