top of page

React apps with Redux Toolkit and a short guide to reducers with createSlice

Updated: May 12, 2023

CreateSlice API of Redux Toolkit Query 🧰

We will create a project implementing redux logic, Redux Toolkit, and a powerful tool for data fetching and data caching called "RTK Query".


Some front-end Frameworks like React, Angular, or Vue, have a system of components where each one internally manages its own states, and of course, as the application becomes complex, its state management becomes complex as well.


¡Redux was the solution to this problem!

This popular state management library works with a kind of main "store" where all the states of the application are located and each of the components can access this. However, when this store needs to be optimized, the configuration requires, in some cases, a lot of repetitive code. In addition, some other necessary packages that enable scalability are required.


To address these challenges, the Redux team created Redux Toolkit, which accelerates with many best practice configs for Redux beginners or Redux developers who want simple, fast, and clean code.


Redux-Toolkit example with CRUD Application - BezKoder


Redux Toolkit

TALK OF THE WEEK


Features

  • Simple: Includes utilities to simplify common use cases such as store configuration, reducer creation, and immutable update logic.

  • Opinionated: Provides good defaults for store configuration out of the box and includes the most commonly used Redux plugins.

  • Powerful: Takes inspiration from libraries such as Immer to allow you to write immutable update logic in a "mutable" way.

  • Effective: This allows you to focus on the core logic your application needs, so you can do more work with less code.


This is born of the major motivation for the three common concerns about Redux:

  • Setting up the Redux store is too complicated.

  • I have to add a lot of packages for Redux to do anything useful

  • Redux requires too much repetitive code

Redux Toolkit includes a powerful tool for data fetching and data caching called "RTK Query".

Basic Setup

So, get started with Redux Toolkit and set it up in a new React application. Alternatively, to Create React App you can use the:


npx create-react-app my-app --template redux

or create using:


npm init vite

Then, in the existing React App, run:


yarn add @reduxjs/toolkit react-redux
yarn add --dev @types/react

And to run the server:


yarn dev


Store to hold our states

We can create a store.js file in our src folder and add the following code to it:


import { configureStore } from '@reduxjs/toolkit'

export default configureStore({
  reducer: {} //add reducers here
})

The configureStore here replaces the original createStore from Redux. Unlike createStore, configureStore from Redux Toolkit not only creates a store but can also accept reducer functions as arguments and automatically sets up the Redux DevTools Extension for easy debugging.


Once our store is created, which we will need every component in our React app to be able to access it. We can do this using the Provider from the react-redux package we installed.


In our index.js file, we import the Provider and our store.js like so:


import store from './store'
import { Provider } from 'react-redux'

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Adding redux logic

Let's create a counter. Compare the structure and pattern we follow with redux and the way it is done with RTK

  • Create /features/counter folder

  • Create a slice counterSlice.ts


import { createSlice } from "@reduxjs/toolkit";
 
interface CounterState {
 value: number;
}
 
const initialState: CounterState = { value: 0 };
 
const counterSlice = createSlice({
 name: "counter", //the way it will look in the store
 initialState,
 reducers: {
   // we define the logic we are going to have in this reducer
   increment(state) {
     state.value++;
   },
 },
});
 
export const { increment } = counterSlice.actions;
export default counterSlice.reducer;

Let's create a store.ts slice


import { configureStore } from "@reduxjs/toolkit";
import counterReducer from "./counter/conterSlice";
 
//compare with combine reducers, this does it automatically.
export const store = configureStore({
 reducer: {
   counter: counterReducer,
 },
});

// This is a wrapper based on the createStore function, devtools extension, thunk middleware, and some alerts about accidental mutations.
export type RootState = ReturnType<typeof store.getState>;

In the main.tsx file we add the Provider


import { store } from "./features/store";
 
   <Provider store={store}>
     <App />
   </Provider>

This would be the setup that is done only once. And view the counter state through the browser



Add and connect App.tsx with redux

const count = useSelector((state: RootState) => state.counter.value);
const dispatch = useDispatch();

<button type="button" onClick={() => dispatch(increment())}>
   count is: {count}
</button>


Talk about thunks!

"Server cache is not the same as UI state and should be handled differently".

One can see a mix of backend data (which behaves like a cache) and UI state (the data that is not retained when the page is reloaded).


These two types of data are treated as if they were the same. That's where RTK Query comes in. It makes it easy to separate the two and handles the server cache, which allows us to focus on the state of the user interface.


We have seen many of the thunks or sagas patterns to write asynchronous logic; one can talk to the store while making requests. The standard flow and the one most of us know is:

  • Do dispatch an action before making the request.

  • Then we make the request to the server

  • And once the server responds we dispatch either success or failure.

  • And sometimes the last step is fulfillment.


Motivation

Specifically for React, it automatically generates hooks for the defined endpoints.


Redux Toolkit Query Guide:

_________________________________________________________________________________________


¡Thanks for reading!


📍 Connect with us on Instagram 👇


Join our newsletter to receive information about latest technologies trends and job offers

Thanks for subscribing!

bottom of page