-
Hello, i am currently migrating from ContextAPI into Zustand. The transition is super smooth. I am just wondering if this following code is a good practice to achieve this. Can you help ? /**
* Types
*/
export interface RootState {
adminPlace: AdminPlaceState;
addPlace: AddPlaceState;
sponsor: SponsorState;
dispatch: (action: AllActionTypes | Thunk) => void;
}
export type AllDispatchs = (action: AllActionTypes | Thunk) => void;
type Thunk = (dispatch: AllDispatchs) => void | Promise<void>;
export type AllActionTypes =
| AddPlaceActionTypes
| SponsorActionTypes
| AdminPlaceActionTypes;
/**
* Functions
*/
const combineReducers = (state: RootState, action: AllActionTypes) => ({
adminPlace: AdminPlaceReducer(state, action),
addPlace: AddPlaceReducer(state, action),
sponsor: SponsorReducer(state, action)
});
const store = (set: NamedSet<RootState>, get: GetState<RootState>) => ({
addPlace: addPlaceInitialState,
adminPlace: adminPlaceInitialState,
sponsor: sponsorInitialState,
dispatch: (action: AllActionTypes | Thunk) => {
if (typeof action === "function") {
const dispatch = get().dispatch;
return action(dispatch);
}
const result = combineReducers(get(), action);
return set((state) => ({ ...state, ...result }), false, action.type);
}
});
/**
* Selectors
*/
const selectDispatch = (state: RootState) => state.dispatch;
/**
* Hooks
*/
export const useStore =
process.env.NODE_ENV === "production"
? create<RootState>(store)
: create<RootState>(devtools(store));
export const useDispatch = () => useStore(selectDispatch); // i can use it in the whole application ! |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
I believe and i saw that zustand use Immer under the hood... So it's not gonna be a big deal to update only one nested property in this store, right ? |
Beta Was this translation helpful? Give feedback.
-
There is Only one concern is the extra object creation. You want to do |
Beta Was this translation helpful? Give feedback.
There is
redux
middleware, if you prefer.I'm not suggesting it, though. Middleware is hard for typing.
If you are comfortable with the way you are doing, it's good.
Only one concern is the extra object creation. You want to do
return set(result, false, action.type);
, right?