--- title: Zustand TypeScript Gotchas description: Common TypeScript gotchas I run into when using Zustand stores. url: https://mattrossman.com/2024/02/07/zustand-typescript-gotchas/ image: https://mattrossman.com/open-graph/2024/02/07/zustand-typescript-gotchas.png --- # Zustand TypeScript Gotchas Feb 7, 2024 There’s a couple gotchas I often face when using [Zustand](https://github.com/pmndrs/zustand) in my projects. I’m documenting them here for future Matt’s sake. - [Usage with React Context](https://mattrossman.com/2024/02/07/zustand-typescript-gotchas/#usage-with-react-context) - [Usage with Middleware](https://mattrossman.com/2024/02/07/zustand-typescript-gotchas/#usage-with-middleware) - [Complete Example](https://mattrossman.com/2024/02/07/zustand-typescript-gotchas/#complete-example) and [TypeScript Playground](https://www.typescriptlang.org/play?#code/JYWwDg9gTgLgBAJQKYEMDGMA0cDecCuAzkgMowoxLZFICiAZvUhtmlKpQMIQB2lAHlgLFufJILgBfOPSgQQcAOTt0MRXAD0GuDACeYJIQBccAIwAOAHQAmSwAYAUKEixccNh1IxoVYV5-YegZwZD4AgmDAUjJyCooAXkTkPAAm6lo6+oYmACyWeTlO4NDweIT4AEaEbMAVSADqwDAAFiRIADbM3lDRsvJKiYTJKRogwCkpnQDuKOzp2kHZcAX5Dg6LcACyuqHscAC8uA4AkGgQ+HwmPPggdVAnwDweIEiXcAAUAJQHAHxwAG4QcYOSRregXDDAXjuFSUba7JBfI7HdgwfBQHgwzwIgA88O6SB+X3eJ2O5SqNTqjRabU6GGg73exBg332f3eOFJp3ObzsmC5j2erxgJiRbLgzMZQwoSFZ7LwZwuIol5EolkVfDgAGozFJPp9+cdjpJ9YbPiC1ht8eFIgdEEg0RiACpZHGLCD0LEy63sH5rM48IZbHYE0QCeCHDwysPiGB4kM2qIAHzg13a7SJafa5oc4hc8HBTxgUMxPqQAAU5P9xkgoBz3M1gO0UuxMZITArG83WyZkKpLH2MAA5CApJB65EBoMAbSGPgAunaaGQZe8o3CE+xzSiHejMSSjfGETHBJZKxBq2Oev8UO18Eh9jg5+xJD8cGguy3XpIcRoyyeYDPKsaygP1jnNUFc34fMZAhYtoRoMsvhMMsoJgwtIQQ4gyxxJ0iWIOlulFaVKBQzdZV+OAnU+EwnTQkpYKLEs-BwvCmQ6LpoAAfmI1UkDIhE5So75OW5QN4GfcdDhoAD3n-Xhw23YBPSZAkDn2Q4s2+Fo5CmVMkD02goDkOsACJNmAQhCEeABzOAjwJc9L1rH5TJzHdHUxZcCVUgIJQ4+koAAQggtY8wYjD4K87DyNkkSTinCS1OkkQFNjOTYrSwQlJUyT1M0-B0205pdP0wzjIZczLOsng7IcnwnJA1z3NRPcVR8C16NcSLmPkwMblrJFRMSlUZSXGKESRDIbIdOBhWAPZJIS3ggw1CMWPIqU+KEkikHVHkWU0bQCK6CUDDQZTgDQOAmiQEA1jEoM8pSpA+vDL4ThoBgmAwRkhNEjy2skyxyWqKBakRLlVJlHa+P2pVDSNNcDv+rlHogTpLHaCAbPeUy1qMUzWBRo6JUqMGIbgKYmmafzCOgLlJER7cmbgad5xa3cMXssA3zWn8NF5kEgA) # Usage with React Context The simplest usage of Zustand is the `create` function that creates a global state hook. In some cases it’s preferable to scope this state explicity with React Context. Their README shows how to achieve this with top level store ([source](https://github.com/pmndrs/zustand/blob/27bffb1fba9de4c958f4a4b4d31c20e54e579fc0/readme.md#react-context)). I prefer putting it in `useState` so that each provider owns a separate copy of the store, making providers more reusable. ``` type MyStore = { count: number increment: () => void } function createMyStore() { return createStore((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })) } type MyStoreApi = ReturnType const MyStoreContext = createContext(null) export function MyStoreProvider({ children }: { children: React.ReactNode }) { const [store] = useState(createMyStore) return ( {children} ) } ``` Usually with vanilla store you need to hand it to Zustand’s `useStore` to consume it. Add in React’s `useContext` and now you have to call two hooks each time you read state. ``` import { useContext } from "react" import { useStore } from "zustand" function MyStoreConsumer() { /** * I don't want to do this everywhere I read state */ const store = useContext(MyStoreContext) const count = useStore(store, (state) => state.count) return

{count}

} ``` In order to create a bounded hook for this vanilla store, you can take advantage of [function overloads](https://www.typescriptlang.org/docs/handbook/2/functions.html#function-overloads) and a non-null assertion to please the compiler and linter. I thought I was pretty clever for coming up with these types, but while writing this post I realized this exact pattern is already documented in [Zustand’s TypeScript Guide](https://github.com/pmndrs/zustand/blob/27bffb1fba9de4c958f4a4b4d31c20e54e579fc0/docs/guides/typescript.md#bounded-usestore-hook-for-vanilla-stores)—d’oh! ``` // The first two lines are "Overload Signatures", the third is the "Implementation Signature" export function useMyStore(): MyStore export function useMyStore(selector: (state: MyStore) => T): T export function useMyStore(selector?: (state: MyStore) => T) { const store = useContext(MyStoreContext) if (store === null) throw new Error("Missing ") // Non-null assertion silences `useStore` complaint about second argument being `undefined` (not actually a runtime issue) return useStore(store, selector!) } ``` Now we can read our state just like we would with the hook produced from `create`. ``` function MyStoreConsumer() { const state = useMyStore() // get entire store // ^? const store: MyStore const count = useMyStore((state) => state.count) // select specific item // ^? const count: number return

{count}

} ``` You may also want a hook that simply returns the entire store object from context, so you call call its imperative methods like `.getState`, `.setState` and `.subscribe` ``` export function useMyStoreContext() { const store = useContext(MyStoreContext) if (store === null) throw new Error("Missing ") return store } function MyStoreConsumer() { const store = useMyStoreContext() useEffect(() => { return store.subscribe(console.log) }, []) return null } ``` # Usage with Middleware When using TypeScript, you should use the curried version of create/createStore. This means calling `create()(...)` instead of `create()`. Note the extra pair of parenthesis. The reasoning is explained in more detail in their [TypeScript guide](https://github.com/pmndrs/zustand/blob/27bffb1fba9de4c958f4a4b4d31c20e54e579fc0/docs/guides/typescript.md#basic-usage). I didn’t notice this at first because the non-curried version works too, until you try using middleware and face some dense type errors: ``` import { create } from "zustand" import { subscribeWithSelector } from "zustand/middleware" const useStore = create( subscribeWithSelector((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })), ) // Error: Argument of type 'StateCreator' is not assignable to parameter of type 'StateCreator'. ``` Simply add in those extra parenthesis and you’ll be good to go: ``` import { create } from "zustand" import { subscribeWithSelector } from "zustand/middleware" const useStore = create()( subscribeWithSelector((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })), ) ``` # Complete Example ``` import { useState, createContext, useContext, useEffect } from "react" import { createStore, useStore, type StoreApi } from "zustand" import { subscribeWithSelector } from "zustand/middleware" type MyStore = { count: number increment: () => void } function createMyStore() { return createStore()( subscribeWithSelector((set) => ({ count: 0, increment: () => set((state) => ({ count: state.count + 1 })), })), ) } type MyStoreApi = ReturnType const MyStoreContext = createContext(null) export function MyStoreProvider({ children }: { children: React.ReactNode }) { const [store] = useState(createMyStore) return ( {children} ) } export function useMyStore(): MyStore export function useMyStore(selector: (state: MyStore) => T): T export function useMyStore(selector?: (state: MyStore) => T) { const store = useContext(MyStoreContext) if (store === null) throw new Error("Missing ") return useStore(store, selector!) } export function useMyStoreContext() { const store = useContext(MyStoreContext) if (store === null) throw new Error("Missing ") return store } export function MyStoreConsumer() { const state = useMyStore() // get entire store const count = useMyStore((state) => state.count) // select specific item const store = useMyStoreContext() useEffect(() => { return store.subscribe( (state) => state.count, (count) => { console.log("count:", count) // subscribe with selector }, ) }, []) return

{count}

} ```