Redux is Dead: Long Live Redux Toolkit

Redux is Dead: Long Live Redux Toolkit

In this article, let’s learn about Redux Toolkit, or as the development team calls it, “the official, opinionated, batteries-included toolset for efficient Redux development”.

What is Redux & How it Works

Most web developers would probably have heard of Redux, a popular state management library. It first came to the front-end world in 2015 as the revolutionary state management solution built by Dan Abramov and Andrew Clark.

In front-end frameworks like React, Angular or Vue, each component internally manages their own states. As the app gets more complex, managing states across many components becomes tedious and difficult. Redux became the solution to this issue.

Redux works by providing a centralized ‘store’, which holds all the states within the app. Each component in the app can access this store without having to pass props around in the component tree.

redux-store.pngImage from codecentric

The Redux Flow

The typical Redux flow is as follows:
1. A user interacts with the View to trigger a state update
2. When a state update is required, the View dispatches an action
3. The reducers receive the action from the dispatch and updates the state in the Store according to what is described by the action
4. The View is subscribed to the Store to listen for state changes. The changes are notified via the subscription methods and the View updates its UI accordingly

redux-flow.pngImage from esri

The Redux flow is made up of 3 main components: Actions, Reducers and Store. Understanding the relationship between these components is necessary to know how Redux works.

Actions are JavaScript objects with a required type property and can include custom properties where needed. They are only used to describe what happened to the state, they are not responsible for changing them. Some examples of actions:


2{ type: 'ADD_TODO', text: 'This is a new todo' }


4{ type: 'LOGIN', payload: { username: 'foo', password: 'bar' }}

The type of an action is simply a string that describes the action, and the added properties are information that are needed to update the state. An action is dispatched via the store.dispatch(action) method, and reducers handle updating the state.

Reducers are pure functions that takes in the current value of a state, performs the operations on it as instructed by the action, then outputs the new value of the state. They are the ones responsible for changing the value of the state. Here’s a simple example of a reducer function:



3function counterReducer(state = { value: 0 }, action) {

4 switch (action.type) {

5 case 'INCREASE':

6 return { value: state.value + 1 }

7 case 'DECREASE':

8 return { value: state.value - 1 }

9 default:

10 return state

11 }


Finally, the state will be updated in the Store. The Store is where all the states are managed. It can be created in a single line:

1const store = createStore(myComponent);

The components must be subscribed to the Store to listen for state updates to render the states correctly in the UI. The store.subscribe() method adds a change listener that will be called whenever an action is dispatched.

At this point, we can see why Redux was a popular option for state management. Its pattern makes states predictable, as reducers are pure functions, which means the same state and actions passed will always result in the same output.

It is also easily maintainable and scalable due to the strict organization on how each part in the Redux flow should behave and work. Also, there are many other benefits such as efficient testing, easy debugging and better performance that Redux brings to the table.

However, this flexible and high-level state management library comes with a few challenges:
1. Too much code to configure Store to optimized levels/best practices
2. Too much boilerplate code makes code less clean and efficient
3. Too many packages needed to install to build scalable apps
4. Writing actions and reducers becomes more complex and cumbersome in huge applications

To address these challenge, the Redux team came up with Redux Toolkit, the official recommended approach for writing Redux logic. It aims to speed up Redux development by including Redux Core with the packages that they think are essential to build a Redux app. It is an opinionated derivative of Redux, with many best practice configurations for Redux beginners or developers who want simple, fast and clean Redux code.

So let’s get started with Redux Toolkit and set it up with a new React app.

Step 1: Install Packages

To get started with Redux Toolkit and React-Redux packages, you can run the following command on an existing React app:

1npm install @reduxjs/toolkit react-redux

Alternatively, install via Create React App with:

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

Step 2: Create & Initialize Store

Now let’s create a store to hold our states. We can create a store.js file in our src folder and add the following code in it:

1import { configureStore } from '@reduxjs/toolkit'


3export default configureStore({

4 reducer: {}


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

Step 3: Provide Store in React app

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

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

1import store from './store'

2import { Provider } from 'react-redux'



5 <Provider store={store}>

6 <App />

7 </Provider>,

8 document.getElementById('root')


Step 4: Write Reducers and Actions

We can now write some reducer functions and actions for our Redux store.

In the traditional Redux, we usually write reducers and actions separately. For example, a simple reducer and action for a counter app will be written in traditional Redux like so:



2export const Increase = () => ({

3 type: 'INCREASE'



6export const Decrease = () => ({

7 type: 'DECREASE'




2export default (state = 0, action) => {

3 switch (action.type) {

4 case 'INCREASE':

5 return state + 1

6 case 'DECREASE':

7 return state - 1

8 default:

9 return state

10 }


With Redux Toolkit, we can make the code much more concise by using createSlice. Create a counterSlice.js file in the src folder of the app. Both the reducers and actions can be written under a slice like so:

1import { createSlice } from '@reduxjs/toolkit'


3export const counterSlice = createSlice({

4 name: 'counter',

5 initialState: {

6 value: 0

7 },

8 reducers: {

9 increase: state => {

10 state.value += 1

11 },

12 decrease: state => {

13 state.value -= 1

14 }

15 }




19export const { increase, decrease } = counterSlice.actions


21export default counterSlice.reducer

As seen from the code above, defining reducers and actions become cleaner and faster in Redux Toolkit. There is no longer need to use the switch statements to manage the action with its corresponding reducer.

Another thing you may have noticed is that it seems we are now directly mutating the state’s value in the reducer function instead of returning a new value to update the state. This is actually because Redux Toolkit uses the Immer library, which allows writing “mutating” logic in reducers.

For more information on how Immer works, feel free to visit its documentation here.

Step 5: Import Reducer to Store

We have exported our reducers and actions from our counterSlice.js. So let’s import the reducer into our store.js.

1import { configureStore } from '@reduxjs/toolkit'

2import counterReducer from '.counterSlice'


4export default configureStore({

5 reducer: {

6 counter: counterReducer

7 }


Step 6: Dispatch Actions from UI

As we have learned earlier, our View triggers an action to be dispatched in order to update a state. In Redux, we use store.dispatch(action) to dispatch an action.

Instead, let’s use React-Redux to use the useDispatch hook to dispatch actions and useSelector to read data from the store.

Create a Counter.js file in our src folder to represent our Counter component. In this file, we will import our useDispatch and useSelector hooks from React-Redux. We will also import our actions from our counterSlice.js.

1import { useSelector, useDispatch } from 'react-redux'

2import { decrease, increase } from './counterSlice'

Then, our Counter function will initialize our 2 hooks and return UI elements with our dispatch(action) triggered when clicked.

1export function Counter() {

2 const count = useSelector(state => state.counter.value)





7 const dispatch = useDispatch()



10 return (

11 <div>

12 <button onClick={() => dispatch(increase())}>

13 Increase

14 </button>

15 <p>{count}<p>

16 <button onClick={() => dispatch(decrease())}>

17 Decrease

18 </button>

19 </div>

20 )


Open Source Session Replay

Debugging a web application in production may be challenging and time-consuming. OpenReplay is an Open-source alternative to FullStory, LogRocket and Hotjar. It allows you to monitor and replay everything your users do and shows how your app behaves for every issue.
It’s like having your browser’s inspector open while looking over your user’s shoulder.
OpenReplay is the only open-source alternative currently available.


Happy debugging, for modern frontend teams – Start monitoring your web app for free.


Redux Toolkit is a great option for both beginners and developers who wants to reduce the amount of boilerplate code in Redux. It allows us to write cleaner and more readable code while keeping the Redux flow and pattern.

Thank you for reading. I hope this article has been helpful in getting you started with understanding Redux and using Redux Toolkit in your applications. Cheers!

Source link

Leave a reply

Please enter your comment!
Please enter your name here