Redux is a state management library used to manage and share data across components through a centralized store using actions and reducers. Redux Toolkit (RTK) is the officially recommended way to write Redux code, providing built-in utilities and boilerplate reduction to make state management simpler, cleaner, and more efficient.
Issues with basic Redux
- Configuring a Redux store is too complicated
- Have to add a lot of packages to build a large-scale application
- Redux requires too much boilerplate code which makes it cumbersome to write efficient and clean code.
Reasons to prefer Redux Toolkit
- Simplified Logic: Leverages a modern, hook-based API to eliminate complex manual implementations.
- Mutable-style Reducers: Uses Immer internally, allowing you to write intuitive, mutable-style code that safely handles immutable state updates.
- Reduced Boilerplate: Significantly minimizes repetitive code, resulting in a cleaner and more maintainable codebase.
- Built-in Data Fetching: Includes RTK Query to automate caching and request management, effectively replacing manual Thunks.
- Optimized Tooling: Comes pre-configured with Redux DevTools and essential utilities to streamline development.
To install Redux Toolkit, use the command:
npm install @reduxjs/toolkit
It also includes dependencies such as immer, redux, redux-thunk, and reselect.
To create a new project, use the command:
npx create-react-app my-app --template redux
Important features provided with RTK
- Automatic support for Redux-thunk, Redux DevTools Extension, and default middleware is provided by configureStore() function
- Support for the immer library that allows writing the immutable code mutably is provided by createReducer() utility.
- create action and create Reducer functions are replaced with a single function called createSlice() function.
- createAsyncThunk() that takes Redux strings as arguments and returns a Promise.
- CRUD operations are performed using createEntityAdapter() utility.
Comparison Between Redux and Redux Toolkit
Comparing Store and Reducers
- Redux: Creating Store and reducers.
- Redux Toolkit: Creating Store and reducers.
Comparing Redux DevTools Extension
- React: You have to add a predefined statement while creating the store to access the Redux DevTools.
- Redux Toolkit: It provides automatic support for Redux DevTools Extension.
Comparing modification of states
- Redux: We need to manually handle and change the state immutably.
- Redux Toolkit: It provides the support for immer.js library which automatically changes the code immutably.