0

From the docs of zustand I found that together with set and get parameters they provide an additional parameter at StateCreator, called api.

Example bellow

import create, { StateCreator } from 'zustand'
import type { Store } from './store.types'

const globalStateCreator: StateCreator<Store> = (set, get, api) => ({
    ...mySlice(set, get, api),
})

What does it stands for? What are the best practices for using it?

Yana Trifonova
  • 586
  • 7
  • 28

1 Answers1

2

If you're using React, you're probably using hooks to do something like this:

const color: PaletteColor = usePaintbrush((s) => s.color);

The hooks make zustand seem more self-contained than it really is. You have a lot of control over the state.

Hooks are limited to components, but you can use the api methods bound to the store from anywhere, imperatively.

// .ts
const color: PaletteColor = usePaintbrush.getState().color[shade];
// .tsx
const color = useRef<PaletteColor>(usePaintbrush.getState().color[shade]);
useEffect(() => usePaintbrush.subscribe((s) => (color.current = s.color[shade])), [shade])

Store actions are not required to be in the store either!

// at module level
const setColor = (color: PaletteColor) => usePaintbrush.setState({ color })

You're unlikely to touch the api parameter unless you're creating a middleware.


Docs cover specific example usage with the persist middleware

The persist api enables you to do numbers of interactions with the persist middleware from inside or outside a React component.


references (updated #1033):

dubble
  • 89
  • 1
  • 5