Unverified Commit 781fa774 authored by Niklas Ziermann's avatar Niklas Ziermann Committed by GitHub

examples: improve zustand example (#58696)

Co-authored-by: 's avatarLee Robinson <me@leerob.io>
parent 779a3734
...@@ -2,7 +2,7 @@ ...@@ -2,7 +2,7 @@
This example shows how to integrate Zustand in Next.js. This example shows how to integrate Zustand in Next.js.
This is an example on how you can use Zustand that also works with Next.js. This is an example on how you can use Zustand with Next.js.
All client components have access to the Zustand store using `useStore()` returned `store.ts` file. All client components have access to the Zustand store using `useStore()` returned `store.ts` file.
......
import StoreProvider from '@/lib/StoreProvider' import StoreProvider from '@/lib/storeProvider'
export default function RootLayout({ export default function RootLayout({
children, children,
...@@ -8,7 +8,9 @@ export default function RootLayout({ ...@@ -8,7 +8,9 @@ export default function RootLayout({
return ( return (
<html> <html>
<body> <body>
<StoreProvider>{children}</StoreProvider> <StoreProvider lastUpdate={new Date().getTime()}>
{children}
</StoreProvider>
</body> </body>
</html> </html>
) )
......
.clock {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
border-radius: 4px;
}
.light {
background-color: #333;
}
...@@ -2,44 +2,35 @@ ...@@ -2,44 +2,35 @@
import useInterval from '../lib/useInterval' import useInterval from '../lib/useInterval'
import { useStore } from '../lib/store' import { useStore } from '../lib/store'
import { useShallow } from 'zustand/react/shallow'
import './clock.css'
const useClock = () => { function useClock() {
return useStore((store) => ({ return useStore(
useShallow((store) => ({
lastUpdate: store.lastUpdate, lastUpdate: store.lastUpdate,
light: store.light, light: store.light,
})) }))
)
} }
const formatTime = (time: number) => { function formatTime(time: number) {
// cut off except hh:mm:ss // hh:mm:ss
return new Date(time).toJSON().slice(11, 19) return new Date(time).toJSON().slice(11, 19)
} }
const Clock = () => { function Clock() {
const { lastUpdate, light } = useClock() const { lastUpdate, light } = useClock()
// alternative way to fetch single piece of state:
const tick = useStore((store) => store.tick) const tick = useStore((store) => store.tick)
// Tick the time every second
useInterval(() => { useInterval(() => {
tick(Date.now(), true) tick(Date.now())
}, 1000) }, 1000)
return ( return (
<div className={light ? 'light' : ''}> <div className={`clock ${light ? 'light' : ''}`}>
{formatTime(lastUpdate)} {formatTime(lastUpdate)}
<style jsx>{`
div {
padding: 15px;
display: inline-block;
color: #82fa58;
font: 50px menlo, monaco, monospace;
background-color: #000;
}
.light {
background-color: #999;
}
`}</style>
</div> </div>
) )
} }
......
'use client' 'use client'
import { useStore } from '../lib/store' import { useStore } from '../lib/store'
import { useShallow } from 'zustand/react/shallow'
const useCounter = () => { function useCounter() {
return useStore((store) => ({ return useStore(
useShallow((store) => ({
count: store.count, count: store.count,
increment: store.increment, increment: store.increment,
decrement: store.decrement, decrement: store.decrement,
reset: store.reset, reset: store.reset,
})) }))
)
} }
const Counter = () => { function Counter() {
const { count, increment, decrement, reset } = useCounter() const { count, increment, decrement, reset } = useCounter()
return ( return (
<div> <div>
......
'use client' 'use client'
import { type PropsWithChildren, useRef } from 'react' import { type PropsWithChildren, useRef } from 'react'
import type { StoreType } from './store' import type { StoreInterface, StoreType } from './store'
import { initializeStore, Provider } from './store' import { initializeStore, Provider } from './store'
const StoreProvider = ({ children, ...props }: PropsWithChildren) => { export interface PreloadedStoreInterface
extends Pick<StoreInterface, 'lastUpdate'> {}
export default function StoreProvider({
children,
...props
}: PropsWithChildren<PreloadedStoreInterface>) {
const storeRef = useRef<StoreType>() const storeRef = useRef<StoreType>()
if (!storeRef.current) { if (!storeRef.current) {
...@@ -13,5 +19,3 @@ const StoreProvider = ({ children, ...props }: PropsWithChildren) => { ...@@ -13,5 +19,3 @@ const StoreProvider = ({ children, ...props }: PropsWithChildren) => {
return <Provider value={storeRef.current}>{children}</Provider> return <Provider value={storeRef.current}>{children}</Provider>
} }
export default StoreProvider
import { createContext, useContext } from 'react' import { createContext, useContext } from 'react'
import { createStore, useStore as useZustandStore } from 'zustand' import { createStore, useStore as useZustandStore } from 'zustand'
import { PreloadedStoreInterface } from './storeProvider'
interface StoreInterface { export interface StoreInterface {
lastUpdate: number lastUpdate: number
light: boolean light: boolean
count: number count: number
tick: (lastUpdate: number, light: boolean) => void tick: (lastUpdate: number) => void
increment: () => void increment: () => void
decrement: () => void decrement: () => void
reset: () => void reset: () => void
} }
const getDefaultInitialState = () => ({ function getDefaultInitialState() {
lastUpdate: Date.now(), return {
lastUpdate: new Date(1970, 1, 1).getTime(),
light: false, light: false,
count: 0, count: 0,
}) } as const
}
export type StoreType = ReturnType<typeof initializeStore> export type StoreType = ReturnType<typeof initializeStore>
const zustandContext = createContext<StoreType | null>(null) const storeContext = createContext<StoreType | null>(null)
export const Provider = zustandContext.Provider export const Provider = storeContext.Provider
export const useStore = <T>(selector: (state: StoreInterface) => T) => { export function useStore<T>(selector: (state: StoreInterface) => T) {
const store = useContext(zustandContext) const store = useContext(storeContext)
if (!store) throw new Error('Store is missing the provider') if (!store) throw new Error('Store is missing the provider')
return useZustandStore(store, selector) return useZustandStore(store, selector)
} }
export const initializeStore = ( export function initializeStore(preloadedState: PreloadedStoreInterface) {
preloadedState: Partial<StoreInterface> = {}
) => {
return createStore<StoreInterface>((set, get) => ({ return createStore<StoreInterface>((set, get) => ({
...getDefaultInitialState(), ...getDefaultInitialState(),
...preloadedState, ...preloadedState,
tick: (lastUpdate, light) => { tick: (lastUpdate) =>
set({ set({
lastUpdate, lastUpdate,
light: !!light, light: !get().light,
}) }),
}, increment: () =>
increment: () => {
set({ set({
count: get().count + 1, count: get().count + 1,
}) }),
}, decrement: () =>
decrement: () => {
set({ set({
count: get().count - 1, count: get().count - 1,
}) }),
}, reset: () =>
reset: () => {
set({ set({
count: getDefaultInitialState().count, count: getDefaultInitialState().count,
}) }),
},
})) }))
} }
...@@ -2,7 +2,10 @@ ...@@ -2,7 +2,10 @@
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/
const useInterval = (callback: () => void, delay: number | undefined) => { export default function useInterval(
callback: () => void,
delay: number | undefined
) {
const savedCallback = useRef<typeof callback>() const savedCallback = useRef<typeof callback>()
useEffect(() => { useEffect(() => {
...@@ -18,5 +21,3 @@ const useInterval = (callback: () => void, delay: number | undefined) => { ...@@ -18,5 +21,3 @@ const useInterval = (callback: () => void, delay: number | undefined) => {
} }
}, [delay]) }, [delay])
} }
export default useInterval
{ {
"compilerOptions": { "compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"], "lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true, "allowJs": true,
"skipLibCheck": true, "skipLibCheck": true,
......
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