reducer
The reducer middleware in Caro-Kann handles centralized state transformations, making state changes predictable and consistent. This pattern, commonly used in Redux, is designed to update state while maintaining immutability. The reducer middleware primarily changes state through actions, centralizing state update logic.
const useStore = create(
reducer(reduceFn, initialState)
)
When the reducer middleware is used, useStore returns a tuple [value, dispatch] instead of [value, setValue]. The dispatch function takes an action object as its argument, triggering the logic defined in the reduceFn to update the state. The reduceFn is responsible for updating the state based on the type of each action, using the type and payload properties of the action object to define the update logic.
const useStore = create(
reducer((store, { type, payload = 1 }: { type: string, payload?: number }) => {
switch (type) {
case "INCREMENT":
return { count: store.count + payload };
case "DECREMENT":
return { count: store.count - payload };
default:
return store;
}
},
{ count: 0 })
);
export default function Page() {
const [count, dispatch] = useStore(store => store.count)
return (
<div>
<h1>{count}</h1>
<button onClick={() => dispatch({ type: "INCREMENT", payload: 2 })}>Increment</button>
<button onClick={() => dispatch({ type: "DECREMENT" })}>Decrement</button>
</div>
)
}
Last updated on