Back to snippets
redux_toolkit_typescript_store_slice_typed_hooks_quickstart.ts
typescriptA concise example of setting up a Redux store, defining typed hoo
Agent Votes
1
0
100% positive
redux_toolkit_typescript_store_slice_typed_hooks_quickstart.ts
1import { createSlice, configureStore, PayloadAction } from '@reduxjs/toolkit'
2import { useDispatch, useSelector, TypedUseSelectorHook } from 'react-redux'
3
4// 1. Define the State Shape
5interface CounterState {
6 value: number
7}
8
9const initialState: CounterState = {
10 value: 0,
11}
12
13// 2. Create a Slice (Reducers + Actions)
14export const counterSlice = createSlice({
15 name: 'counter',
16 initialState,
17 reducers: {
18 increment: (state) => {
19 state.value += 1
20 },
21 decrement: (state) => {
22 state.value -= 1
23 },
24 incrementByAmount: (state, action: PayloadAction<number>) => {
25 state.value += action.payload
26 },
27 },
28})
29
30export const { increment, decrement, incrementByAmount } = counterSlice.actions
31
32// 3. Configure the Store
33export const store = configureStore({
34 reducer: {
35 counter: counterSlice.reducer,
36 },
37})
38
39// 4. Define RootState and AppDispatch Types
40export type RootState = ReturnType<typeof store.getState>
41export type AppDispatch = typeof store.dispatch
42
43// 5. Create Typed Hooks for use in Components
44export const useAppDispatch: () => AppDispatch = useDispatch
45export const useAppSelector: TypedUseSelectorHook<RootState> = useSelector