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 @@
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.
......
import StoreProvider from '@/lib/StoreProvider'
import StoreProvider from '@/lib/storeProvider'
export default function RootLayout({
children,
......@@ -8,7 +8,9 @@ export default function RootLayout({
return (
<html>
<body>
<StoreProvider>{children}</StoreProvider>
<StoreProvider lastUpdate={new Date().getTime()}>
{children}
</StoreProvider>
</body>
</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 @@
import useInterval from '../lib/useInterval'
import { useStore } from '../lib/store'
const useClock = () => {
return useStore((store) => ({
lastUpdate: store.lastUpdate,
light: store.light,
}))
import { useShallow } from 'zustand/react/shallow'
import './clock.css'
function useClock() {
return useStore(
useShallow((store) => ({
lastUpdate: store.lastUpdate,
light: store.light,
}))
)
}
const formatTime = (time: number) => {
// cut off except hh:mm:ss
function formatTime(time: number) {
// hh:mm:ss
return new Date(time).toJSON().slice(11, 19)
}
const Clock = () => {
function Clock() {
const { lastUpdate, light } = useClock()
// alternative way to fetch single piece of state:
const tick = useStore((store) => store.tick)
// Tick the time every second
useInterval(() => {
tick(Date.now(), true)
tick(Date.now())
}, 1000)
return (
<div className={light ? 'light' : ''}>
<div className={`clock ${light ? 'light' : ''}`}>
{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>
)
}
......
'use client'
import { useStore } from '../lib/store'
import { useShallow } from 'zustand/react/shallow'
const useCounter = () => {
return useStore((store) => ({
count: store.count,
increment: store.increment,
decrement: store.decrement,
reset: store.reset,
}))
function useCounter() {
return useStore(
useShallow((store) => ({
count: store.count,
increment: store.increment,
decrement: store.decrement,
reset: store.reset,
}))
)
}
const Counter = () => {
function Counter() {
const { count, increment, decrement, reset } = useCounter()
return (
<div>
......
'use client'
import { type PropsWithChildren, useRef } from 'react'
import type { StoreType } from './store'
import type { StoreInterface, StoreType } 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>()
if (!storeRef.current) {
......@@ -13,5 +19,3 @@ const StoreProvider = ({ children, ...props }: PropsWithChildren) => {
return <Provider value={storeRef.current}>{children}</Provider>
}
export default StoreProvider
import { createContext, useContext } from 'react'
import { createStore, useStore as useZustandStore } from 'zustand'
import { PreloadedStoreInterface } from './storeProvider'
interface StoreInterface {
export interface StoreInterface {
lastUpdate: number
light: boolean
count: number
tick: (lastUpdate: number, light: boolean) => void
tick: (lastUpdate: number) => void
increment: () => void
decrement: () => void
reset: () => void
}
const getDefaultInitialState = () => ({
lastUpdate: Date.now(),
light: false,
count: 0,
})
function getDefaultInitialState() {
return {
lastUpdate: new Date(1970, 1, 1).getTime(),
light: false,
count: 0,
} as const
}
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) => {
const store = useContext(zustandContext)
export function useStore<T>(selector: (state: StoreInterface) => T) {
const store = useContext(storeContext)
if (!store) throw new Error('Store is missing the provider')
return useZustandStore(store, selector)
}
export const initializeStore = (
preloadedState: Partial<StoreInterface> = {}
) => {
export function initializeStore(preloadedState: PreloadedStoreInterface) {
return createStore<StoreInterface>((set, get) => ({
...getDefaultInitialState(),
...preloadedState,
tick: (lastUpdate, light) => {
tick: (lastUpdate) =>
set({
lastUpdate,
light: !!light,
})
},
increment: () => {
light: !get().light,
}),
increment: () =>
set({
count: get().count + 1,
})
},
decrement: () => {
}),
decrement: () =>
set({
count: get().count - 1,
})
},
reset: () => {
}),
reset: () =>
set({
count: getDefaultInitialState().count,
})
},
}),
}))
}
......@@ -2,7 +2,10 @@
import { useEffect, useRef } from 'react'
// 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>()
useEffect(() => {
......@@ -18,5 +21,3 @@ const useInterval = (callback: () => void, delay: number | undefined) => {
}
}, [delay])
}
export default useInterval
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": 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