On this Page
Why Use TypeScript in State Management
Using TypeScript with your state management solution:
- Prevents silent bugs from mistyped property names
- Helps you refactor code safely
- Improves auto-completion in IDEs
- Brings structure to growing apps
Using TypeScript with Zustand
Install Zustand:
npm install zustand
Creating a Typed Zustand Store
import { create } from "zustand";
type BearState = {
count: number;
increase: () => void;
};
const useBearStore = create<bearstate>((set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 }))
}));
// In your component:
const count = useBearStore((s) => s.count);
Zustandβs API is simple and works beautifully with TypeScript.
Using TypeScript with Redux Toolkit
Install Redux Toolkit and types:
npm install @reduxjs/toolkit react-redux
npm install --save-dev @types/react-redux
Create a slice with typed state:
import { createSlice, PayloadAction } from "@reduxjs/toolkit";
interface CounterState {
value: number;
}
const initialState: CounterState = { value: 0 };
const counterSlice = createSlice({
name: "counter",
initialState,
reducers: {
increment(state) {
state.value++;
},
addBy(state, action: PayloadAction<number>) {
state.value += action.payload;
}
}
});
export const { increment, addBy } = counterSlice.actions;
export default counterSlice.reducer;
Typing Redux Slices and Selectors
In store.ts:
import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counterSlice";
export const store = configureStore({
reducer: {
counter: counterReducer
}
});
export type RootState = ReturnType<typeof store.getstate>;
export type AppDispatch = typeof store.dispatch;
In components:
import { useSelector, useDispatch } from "react-redux";
import type { RootState, AppDispatch } from "./store";
const value = useSelector((state: RootState) => state.counter.value);
const dispatch = useDispatch<appdispatch>();
Summary
- Zustand and Redux Toolkit both work great with TypeScript
- Zustand: use generic typing on store creation
- Redux Toolkit: type state, payloads, selectors, and dispatch
- State management becomes predictable and safe with TypeScript
Next up: Lesson 20 β Final Thoughts, Best Practices, and Resources