Redux Toolkit
- React Native course
- Advanced
- Lesson 50/83
- 5 min
Learn simplified Redux with Redux Toolkit.
Redux Toolkit
Redux Toolkit (RTK) is the official package that simplifies the verbose boilerplate of classic Redux. Creating a store with configureStore and writing reducers with createSlice needs less code. In classic Redux every action type, action creator and reducer was written separately; RTK gathers them in one place.
Install with npm install @reduxjs/toolkit react-redux. configureStore takes a reducer key and sets up middleware automatically. The react-redux package provides the Provider and the useDispatch, useSelector hooks. RTK is the default starting point for modern Redux projects.
A store with configureStore
You create a store with configureStore({ reducer: { counter: counterReducer } }). The reducer field is an object; each key represents a slice. RTK combines them automatically; you do not need combineReducers.
You wrap the store at the app root with <Provider store={store}>. This way all components can access the store via useDispatch and useSelector. This pattern is done once in the App component's return.
Practice Create the store
Complete the empty file. Import configureStore from @reduxjs/toolkit. Define export const store with configureStore({ reducer: { counter: counterReducer } }). Assume counterReducer is exported elsewhere.
Starter code
import { counterReducer } from './counterSlice';
// create the storeSample solution
import { configureStore } from '@reduxjs/toolkit';
import { counterReducer } from './counterSlice';
export const store = configureStore({
reducer: { counter: counterReducer },
});Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match the RTK parts
| Term | Meaning |
|---|---|
configureStore |
Creates the store |
createSlice |
Writes a slice |
Provider |
Applies the store |
react-redux |
Provides the hooks |
2 What does RTK reduce?
- The amount of boilerplate code
- Animation quality Correct answer
- The app size (none)
- Camera resolution
Explanation: RTK reduces the amount of boilerplate code.
3 The configureStore call
const store = configureStore({ reducer: { ____: counterReducer } });
const store = configureStore({ reducer: { counter: counterReducer } });
Explanation: counter is the slice name.