Skip to content

Commit

Permalink
feat: new zustand store hydration method
Browse files Browse the repository at this point in the history
  • Loading branch information
fluid-design-io committed Jun 24, 2024
1 parent 7b019da commit da1b27d
Showing 1 changed file with 31 additions and 0 deletions.
31 changes: 31 additions & 0 deletions apps/web/context/color-store-provider.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
'use client'

import { createContext, useContext, useRef } from 'react'

import { ColorStore, ColorsHydrateValues, createColorStore } from '@/store/store'
import { useStore } from 'zustand'

export type ColorStoreApi = ReturnType<typeof createColorStore>

const ColorStoreContext = createContext<ColorStoreApi | null>(null)

export interface ColorStoreProviderProps extends ColorsHydrateValues {
children: any
}

export function ColorStoreProvider({ children, ...rest }: ColorStoreProviderProps) {
const storeRef = useRef<ColorStoreApi>()
if (!storeRef.current) {
storeRef.current = createColorStore(rest)
}

return <ColorStoreContext.Provider value={storeRef.current}>{children}</ColorStoreContext.Provider>
}

export const useColorStore = <T,>(selector: (store: ColorStore) => T): T => {
const storeContent = useContext(ColorStoreContext)
if (!storeContent) {
throw new Error('useColorStore must be used within a ColorStoreProvider')
}
return useStore(storeContent, selector)
}

0 comments on commit da1b27d

Please sign in to comment.