Skip to content

Instantly share code, notes, and snippets.

@marlosirapuan
Created August 31, 2023 18:09
Show Gist options
  • Save marlosirapuan/3cd2cc36b5170bf35ce973df57ca5bfe to your computer and use it in GitHub Desktop.
Save marlosirapuan/3cd2cc36b5170bf35ce973df57ca5bfe to your computer and use it in GitHub Desktop.
Context App Provider with zustand in Typescript
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