Generic State Management Patterns
What you'll learn: How popular state management libraries use generics to create type-safe state and actions.
The Pattern Behind Redux, Zustand, and Friends
If you've used state management libraries, you've probably noticed they magically know the shape of your state and actions. That magic? Generics.
Libraries like Redux, Zustand, and Jotai all follow a similar pattern: they accept your custom state type as a type parameter, then return perfectly typed selectors, dispatchers, and hooks. This lets one library codebase work with infinite state shapes.
How It Works
The core pattern looks like this:
// Simplified state store pattern
type Store<TState> = {
getState: () => TState;
setState: (partial: Partial<TState>) => void;
subscribe: (listener: (state: TState) => void) => void;
};
function createStore<TState>(initialState: TState): Store<TState> {
let state = initialState;
const listeners: Array<(state: TState) => void> = [];
return {
getState: () => state,
setState: (partial) => {
state = { ...state, ...partial };
listeners.forEach(listener => listener(state));
},
subscribe: (listener) => {
listeners.push(listener);
}
};
}
// Usage with type inference
const userStore = createStore({ name: "Alice", age: 30 });
userStore.setState({ age: 31 }); // ✓ type-safe
// userStore.setState({ invalid: true }); // ✗ error
The library doesn't know what your state looks like — you tell it through TState, and it builds type-safe operations around that shape.
Actions and Reducers
State management often includes actions:
type Action<TType extends string, TPayload = void> = {
type: TType;
payload: TPayload;
};
function createAction<TType extends string, TPayload>(
type: TType,
payload: TPayload
): Action<TType, TPayload> {
return { type, payload };
}
const setUser = createAction("SET_USER", { name: "Bob", age: 25 });
// Type: Action<"SET_USER", { name: string; age: number }>
This pattern lets libraries type-check dispatchers, reducers, and middleware without knowing your specific actions ahead of time.
Key Takeaway: State management libraries use generics to accept your state shape as a type parameter, then build type-safe operations (getters, setters, actions) around it — letting one codebase serve infinite state structures.