Redux Toolkit
While Redux is powerful, setting it up requires a lot of boilerplate code action creators, constants, reducers, and store configuration. **Redux Toolkit** is the official, opinionated toolset for efficient Redux development. It simplifies store setup, reduces boilerplate, and includes best practices out of the box.
What is Redux Toolkit?
Redux Toolkit (RTK) is a package that provides utilities to simplify common Redux tasks. It includes functions like `configureStore`, `createSlice`, and `createAsyncThunk` that make writing Redux logic much cleaner.
Think of Redux Toolkit as the "batteries-included" version of Redux. It gives you everything you need with minimal setup.
Installation
npm install @reduxjs/toolkit react-reduxCreating a Slice
A slice automatically generates actions and reducers based on the reducers you define. It uses Immer internally so you can write "mutating" syntax safely.
import { createSlice } from '@reduxjs/toolkit';
const todosSlice = createSlice({ name: 'todos', initialState: { items: [] }, reducers: { addTodo: (state, action) => { <!-- "Mutating" syntax is safe because Immer handles it --> state.items.push({ id: Date.now(), text: action.payload, completed: false }); }, toggleTodo: (state, action) => { const todo = state.items.find(todo => todo.id === action.payload); if (todo) todo.completed = !todo.completed; } }});
<!-- Export actions and reducer -->export const { addTodo, toggleTodo } = todosSlice.actions;export default todosSlice.reducer;Configuring the Store
`configureStore` sets up the store with good defaults, including Redux DevTools and middleware like redux-thunk.
import { configureStore } from '@reduxjs/toolkit';import todosReducer from './todosSlice';
const store = configureStore({ reducer: { todos: todosReducer, },});Using in React Components
You still use `useSelector` and `useDispatch` the same way.
import { useSelector, useDispatch } from 'react-redux';import { addTodo, toggleTodo } from './todosSlice';
function TodoApp() { const todos = useSelector(state => state.todos.items); const dispatch = useDispatch(); <!-- ... same as before ... -->}Two Minute Drill
- Redux Toolkit is the modern, recommended way to write Redux logic.
- `createSlice` generates actions and reducers automatically with less boilerplate.
- `configureStore` sets up the store with good defaults (DevTools, thunk middleware).
- Redux Toolkit uses Immer internally, allowing you to write simpler mutable-style logic in reducers.
- It's fully compatible with existing React-Redux hooks.
Need more clarification?
Drop us an email at career@quipoinfotech.com
