Why Redux Toolkit?
Redux Toolkit (RTK) was created to solve three common complaints about Redux: 'Configuring a store is too complicated', 'I have to add a lot of packages to get Redux to do anything useful', and 'Redux requires too much boilerplate code'. RTK is now the official, recommended way to write Redux logic.
The Anatomy of a Slice
A 'Slice' is the collection of Redux reducer logic and actions for a single feature in your app. It uses Immer internally, which allows you to write 'mutative' code that is safely converted into immutable updates.
Handling Async Logic with createAsyncThunk
For API calls, RTK provides createAsyncThunk. It generates promise lifecycle action types (pending, fulfilled, and rejected) which you can handle in the extraReducers field of your slice.
RTK Query: The Future of Data Fetching
RTK Query is an optional addon included in the Redux Toolkit package. It is a powerful data fetching and caching tool designed to simplify loading data in a web application, eliminating the need to hand-write fetch logic or manage loading states manually.
| Feature | Standard RTK | RTK Query |
|---|---|---|
| Data Management | Manual (Slices/Thunks) | Automated (Hooks) |
| Caching | Manual implementation | Automatic based on endpoints |
| Loading States | Manual (extraReducers) | Provided automatically (isLoading) |
| Boilerplate | Moderate | Minimal |