-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat: new zustand store hydration method
- Loading branch information
1 parent
7b019da
commit da1b27d
Showing
1 changed file
with
31 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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) | ||
} |