Created
August 31, 2023 18:09
-
-
Save marlosirapuan/3cd2cc36b5170bf35ce973df57ca5bfe to your computer and use it in GitHub Desktop.
Context App Provider with zustand in Typescript
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
import { createContext, useContext } from 'react' | |
import { createStore, StoreApi } from 'zustand' | |
import { immer } from 'zustand/middleware/immer' | |
import { useStoreWithEqualityFn } from 'zustand/traditional' | |
type State = { | |
total: number | |
increase: () => void | |
decrease: () => void | |
} | |
const store = createStore<State>()( | |
immer((set) => ({ | |
total: 0, | |
increase: () => | |
set((state) => { | |
state.total++ | |
}), | |
decrease: () => | |
set((state) => { | |
state.total-- | |
}) | |
})) | |
) | |
const Context = createContext<StoreApi<State>>({} as StoreApi<State>) | |
export const AppProvider = ({ children }: { children: React.ReactNode }) => { | |
return <Context.Provider value={store}>{children}</Context.Provider> | |
} | |
export const useApp = <T,>(selector: (state: State) => T, equalityFn?: (left: T, right: T) => boolean) => { | |
const store = useContext(Context) | |
if (!store) { | |
throw new Error('Context is not provided') | |
} | |
return useStoreWithEqualityFn(store, selector, equalityFn) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment