Skip to main content
Module

x/jotai/docs/guides/nextjs.mdx

👻 Primitive and flexible state management for React
Go to Latest
File
---title: Next.jsdescription: How to use Jotai with Next.jsnav: 3.04---
## Hydration
Jotai has support for hydration of atoms with `useHydrateAtoms`. The documentation for the hook can be seen [here](../utils/use-hydrate-atoms.mdx).
## Sync with router
It's possible to sync Jotai with the router. You can achieve this with `atomWithHash`:
```jsconst 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](https://nextjs.org/docs/api-reference/next/router#routerevents) you want to subscribe to.
## You can't return promises in server side rendering
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.
```jsconst postData = atom((get) => { const id = get(postId) if (isSSR || prefetchedPostData[id]) { return prefetchedPostData[id] || EMPTY_POST_DATA } return fetchData(id) // returns a promise})```
## Examples
### Clock
<CodeSandbox id="snu7n" />### HN Posts
<CodeSandbox id="819n4" />### Next.js repo
```bashnpx create-next-app --example with-jotai with-jotai-app# oryarn create next-app --example with-jotai with-jotai-app```
Here's a [link](https://github.com/vercel/next.js/tree/canary/examples/with-jotai).