What are the main differences between Redux and Redux Toolkit?
Redux Toolkit provides useful abstractions and defaults that reduce boilerplate code compared to Redux. Key differences:
- Redux Toolkit has configureStore() which sets up the store with defaults instead of having to configure it manually.
- It has createReducer() to simplify writing reducers vs switch statements.
- It has createAction() to generate action creators.
- It includes thunk middleware by default.
- It has createSlice() that handles generating action types and action creators.
What are the benefits of using Redux Toolkit over Redux?
Some main benefits:
- Less boilerplate code.
- Easier to write reducers, action creators, and actions.
- Provides good defaults for store setup.
- Includes thunk middleware by default.
- Still allows all customizations you can do with Redux.
How do you create a Redux store using Redux Toolkit?
Use configureStore() and pass in reducer functions created with createReducer():
import { configureStore } from '@reduxjs/toolkit'
const store = configureStore({
reducer: {
counter: createReducer(0, {
increment: (state) => state + 1,
})
}
})
How can you generate boilerplate code like action types and creators with Redux Toolkit?
Use createSlice() and pass in a name, initial state, and reducers object with functions that mutate state:
const counterSlice = createSlice({
name: 'counter',
initialState: 0,
reducers: {
increment: state => state + 1
}
})
This will generate action types like counter/increment
and action creators like counterSlice.actions.increment()
.