Best practices on the updater functions #3154
-
|
Hi, I am currently implementing a single Zustand store with some properties and a single updater function, something like a 'dispatcher' that updates whatever field you want: interface StoreState {
fieldA: string | null
fieldB: string | null
update: (newState: Partial<StoreState>) => void
}
export const useStore = create<StoreState>((set) => ({
fieldA: '',
fieldB: '',
update: (newState) => set(newState),
}))And then, when I need to update a field or more, I call it like this: update({ fieldA: 'something' })
or
update({ fieldA: 'whatever', fieldB: 'another' })This seems to not cause any major problems or re-renders, except for one thing: you could potentially call the 'update' function with another value for the same 'update' function. However, I see it as a developer responsibility and not likely to happen. I know that Zustand describes the use of 'actions', each one of them 'linked' to its primitive value, but... Thank you so much in advance. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 4 replies
-
|
@ivsantos nothing wrong but in that case I'd use |
Beta Was this translation helpful? Give feedback.
@ivsantos nothing wrong but in that case I'd use
useStore.setState(...)function instead