Unverified Commit 0e55bb1a authored by Milan K's avatar Milan K Committed by GitHub

examples: `with-zustand` update to App Router (#58042)

Co-authored-by: 's avatarLee Robinson <me@leerob.io>
parent e224c225
...@@ -2,15 +2,9 @@ ...@@ -2,15 +2,9 @@
This example shows how to integrate Zustand in Next.js. This example shows how to integrate Zustand in Next.js.
Usually splitting your app state into `pages` feels natural but sometimes you'll want to have global state for your app. This is an example on how you can use Zustand that also works with Next.js's universal rendering approach. This is an example on how you can use Zustand that also works with Next.js.
In the first example we are going to display a digital clock that updates every second. The first render is happening in the server and then the browser will take over. To illustrate this, the server rendered clock will have a different background color (black) than the client one (grey). All client components have access to the Zustand store using `useStore()` returned `store.ts` file.
To illustrate SSG, go to `/ssg` and to illustrate SSR go to `/`, those pages are using Next.js data fetching methods to get the date in the server and return it as props to the page, and then the browser will hydrate the store and continue updating the date.
The trick here for supporting universal Zustand is to separate the cases for the client and the server. When we are on the server we want to create a new store every time with the `initialZustandState` returned from the get\*Props methods.
All components have access to the Zustand store using `useStore()` returned `store.ts` file.
## Deploy your own ## Deploy your own
......
import StoreProvider from '@/lib/StoreProvider'
export default function RootLayout({
children,
}: {
children: React.ReactNode
}) {
return (
<html>
<body>
<StoreProvider>{children}</StoreProvider>
</body>
</html>
)
}
import Clock from '../components/clock'
import Counter from '../components/counter'
export default function Page() {
return (
<>
<Clock />
<Counter />
</>
)
}
'use client'
import useInterval from '../lib/useInterval'
import { useStore } from '../lib/store' import { useStore } from '../lib/store'
const useClock = () => { const useClock = () => {
...@@ -14,6 +17,13 @@ const formatTime = (time: number) => { ...@@ -14,6 +17,13 @@ const formatTime = (time: number) => {
const Clock = () => { const Clock = () => {
const { lastUpdate, light } = useClock() const { lastUpdate, light } = useClock()
const tick = useStore((store) => store.tick)
// Tick the time every second
useInterval(() => {
tick(Date.now(), true)
}, 1000)
return ( return (
<div className={light ? 'light' : ''}> <div className={light ? 'light' : ''}>
{formatTime(lastUpdate)} {formatTime(lastUpdate)}
......
'use client'
import { useStore } from '../lib/store' import { useStore } from '../lib/store'
const useCounter = () => { const useCounter = () => {
......
import Link from 'next/link'
import { CSSProperties } from 'react'
const LinkStyle: CSSProperties = { marginRight: '25px' }
const Nav = () => {
return (
<nav>
<Link href="/ssg" style={LinkStyle}>
SSG
</Link>
<Link href="/" style={LinkStyle}>
SSR
</Link>
</nav>
)
}
export default Nav
import useInterval from '../lib/useInterval'
import Clock from './clock'
import Counter from './counter'
import Nav from './nav'
import { useStore } from '../lib/store'
export default function Page() {
const tick = useStore((store) => store.tick)
// Tick the time every second
useInterval(() => {
tick(Date.now(), true)
}, 1000)
return (
<>
<Nav />
<Clock />
<Counter />
</>
)
}
'use client'
import { type PropsWithChildren, useRef } from 'react' import { type PropsWithChildren, useRef } from 'react'
import type { StoreType } from './store' import type { StoreType } from './store'
import { initializeStore, Provider } from './store' import { initializeStore, Provider } from './store'
......
'use client'
import { useEffect, useRef } from 'react' import { useEffect, useRef } from 'react'
// https://overreacted.io/making-setinterval-declarative-with-react-hooks/ // https://overreacted.io/making-setinterval-declarative-with-react-hooks/
......
import StoreProvider from '@/lib/StoreProvider'
import type { AppProps } from 'next/app'
export default function App({ Component, pageProps }: AppProps) {
return (
<StoreProvider {...pageProps.initialZustandState}>
<Component {...pageProps} />
</StoreProvider>
)
}
import { Html, Head, Main, NextScript } from 'next/document'
export default function Document() {
return (
<Html lang="en">
<Head />
<body>
<Main />
<NextScript />
</body>
</Html>
)
}
import type { GetServerSideProps } from 'next'
import Page from '../components/page'
import { initializeStore } from '../lib/store'
export default function Home() {
return <Page />
}
// The date returned here will be different for every request that hits the page,
// that is because the page becomes a serverless function instead of being statically
// exported when you use `getServerSideProps` or `getInitialProps`
export const getServerSideProps: GetServerSideProps = async () => {
const zustandStore = initializeStore()
return {
props: {
// the "stringify and then parse again" piece is required as next.js
// isn't able to serialize it to JSON properly
initialZustandState: JSON.parse(JSON.stringify(zustandStore.getState())),
},
}
}
import { GetStaticProps } from 'next'
import Page from '../components/page'
import { initializeStore } from '../lib/store'
export default function SSG() {
return <Page />
}
// If you build and start the app, the date returned here will have the same
// value for all requests, as this method gets executed at build time.
// You will not see this while in development mode though.
export const getStaticProps: GetStaticProps = () => {
const zustandStore = initializeStore()
return {
props: {
// the "stringify and then parse again" piece is required as next.js
// isn't able to serialize it to JSON properly
initialZustandState: JSON.parse(JSON.stringify(zustandStore.getState())),
},
}
}
...@@ -16,8 +16,13 @@ ...@@ -16,8 +16,13 @@
"incremental": true, "incremental": true,
"paths": { "paths": {
"@/*": ["./src/*"] "@/*": ["./src/*"]
},
"plugins": [
{
"name": "next"
} }
]
}, },
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"] "exclude": ["node_modules"]
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment