Skip to main content

Redux Toolkit steps

create src/state/store.ts with configureStore()

import { configureStore } from "@reduxjs/toolkit"
import rootReducer from "./reducers" // /index.ts

const store = configureStore({
reducer: {
//reducer_key: reducer
}
})

// // Infer & Export types for RootState & AppDispatch
export type RootState = ReturnType<typeof store.getState\>
export type AppDispatch = typeof store.dispatch

Provide store to <App>

... root.render(
<StrictMode\>
<Provider store={store}\>
<App /\>
</Provider\>
</StrictMode\>)

Create reducers inside newer "slice" in src/state/reducers
to get "slice" of state - define initState & reducers applies immer so now can mutate state directly!

import { createSlice } from "@reduxjs/toolkit"
import type { PayloadAction } from "@reduxjs/toolkit"
import { RootState } from "../store"

interface CounterState {
value: number
}

const initialState: CounterState = {
value: 0,
}

export const counterSlice = createSlice({
name: "counter",
// `createSlice` will infer the state type from the `initialState` argument
initialState,
reducers: {
increment: (state) => {
state.value += 1
},
decrement: (state) => {
state.value -= 1
},
// Use the PayloadAction type to declare the contents of `action.payload`
incrementByAmount: (state, action: PayloadAction<number\>) => {
state.value += action.payload
},
},
})

export const { increment, decrement, incrementByAmount } = counterSlice.actions

// Other code such as selectors can use the imported `RootState` type
export const selectCount = (state: RootState) => state.counter.value

export default counterSlice.reducer

References