React-Redux Vs Redux Toolkit


Before getting into this article, I’m assuming that you must be aware of redux basics, but for the sake of those who aren’t aware let’s look into it briefly.

Redux

Redux is a state management library that you can use with any JS library or framework like React, Angular, or Vue. It is one of the hottest libraries in front-end development these days. The documentation states that Redux is a predictable state container for JavaScript apps. In simple words, it’s an application data-flow architecture, rather than a traditional library or a framework like Underscore.js and AngularJS.

Data Flow


Its core building blocks such as a store, actions, and reducers, all come together and make Redux the global state management library.

A state is a read-only object that holds the application data that is shared between components. The only way to change the state is to dispatch an action. An action is an event that describes something that happened in the application.

A reducer is a function that receives the current state and an action object decides how to update the state if necessary, and returns the new state: (state, action) => newState.
The current Redux application state lives in an object called the store.

You can know redux in detail from here.

Now, let’s start with Redux Toolkit and see how it is smarter than Redux.

Redux Toolkit is a SOPE library that stands for Simple, Opinionated, Powerful, and Effective state management library. It allows us to write more efficient code, speed up the development process, and automatically apply the best-recommended practices.

Setup

# NPM npm install @reduxjs/toolkit //or # Yarn yarn add @reduxjs/toolkit

If you want to add Redux Toolkit and React-Redux packages :

npm install @reduxjs/toolkit react-redux

RTK was mainly created to solve the three major issues with 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 difficult to write efficient and clean code.

To understand the concept of the redux toolkit easily let’s see an example of Counter App

[typescript] //1. Create a Redux Store //store.ts import { configureStore } from ‘@reduxjs/toolkit’; import { counterReducer } from ‘./Reducer’; export const store = configureStore({ reducer: { counter: counterReducer, }, }); export type RootState = ReturnType; //2. Provide the Redux Store to App.tsx import { store } from ‘./src/toolkit/store’; import { Provider } from ‘react-redux’; const App = () => { return ( ); }; export default App; //3. create a reducer file Reducer.ts import { createReducer } from ‘@reduxjs/toolkit’; const initialState = { counter: 0 }; export const counterReducer = createReducer(initialState, { increment: (state) => { // No need of action for constant value state. counter += 1; }, incrementByValue: (state, action) => { //here payload is by how much value it will be increment state. counter += action.payload; }, decrement: (state) => { state.counter -= 1; }, }); //4. create a file for UI and to use redux state use useSelector hook and for dispatch action use useDispatch hook from react-redux. import { useDispatch, useSelector } from ‘react-redux’; import { RootState } from ‘../../toolkit/store’; const ReduxToolkitDemo = () => { const dispatch = useDispatch(); const { counter } = useSelector((state: RootState) => state.counter); const addValue = () => { dispatch({ type: ‘increment’ }); }; const subValue = () => { dispatch({ type: ‘decrement’ }); }; const incrementByValue = () => { dispatch({ type: ‘incrementByValue’, payload: 10 }); }; return ( <> Counter={counter} Increment Increment By value Decrement ); }; export default ReduxToolkitDemo; [/typescript]

Redux Toolkit comes with dependencies like immer, redux, redux-thunk, and reselect. It also provides automatic support for Redux Dev-tools Extension and for the immer.js library which is a great tool to deal with immutable objects.

From the above example, a basic comparison between redux and redux-toolkit:

Modifying The State:

//1. Redux: Need to handle manually and change the state immutably. const initialState={counter:0} const handleCounter=(state=initialState,action){ return{ …state, counter: state.counter+1; } } //2. Redux Toolkit: Provides the support for immer.js library which automatically changes the code immutably. const initialState={counter:0} const handleCounter=(state=initialState,action){ return{ counter: state.counter+1; } }

Creating Store and Reducers.

//1. Redux const incrementHandler=(state=0,action)=>{ if(action.type===’INCREMENT’) { return state+1; } return state; } const store = createStore(incrementHandler); store.dispatch({type:’INCREMENT’}); //2. Redux Toolkit // Action Creators const increment= createAction(‘INCREMENT’); const incrementHandler = createReducer(0, { [increment]: state => state + 1 }) const store = configureStore({ reducer: incrementHandler }) store.dispatch(increment());

Some functions or utilities provided by RTK:

 createAction(): Returns an action creator function.

createSlice(): Replace create action and create Reducer functions with a single function.

 configureStore(): Provides automatic support for Redux-thunk, Redux DevTools Extension, and also passes the default middleware.

createReducer(): Provides support for the immer library that allows writing the immutable code mutably.

As you can see, the Redux Toolkit code is simpler and requires less boilerplate code than the Redux code. The various predefined functions speed up the process and save the time required to manage the state of an application.

If you want to know more about Redux Toolkit, please check here.

Latest

SENTRY integration in your React Native App for Error/Crash tracking

Sentry captures data by using an SDK within your...

Recall the concepts of useCallback.

useCallback hook is one of the best hooks offered...

Value of Comments in the code!!

During my journey of Software Development, I am always...

YOLO:Bullet Paced Algorithm

http://sh017.hostgator.tempwebhost.net/media/33949d0e61af4b50f374c534713f56b3 According to world health organization, more than 1.35 million...

Featured

Developing Enterprise Application in Node.js – CJS Vs ESM

Node.js is a popular runtime environment for building server-side...

Integrating your web react applications with their React Native(android and IOS) apps using QR code

Integrating a web application with Android and iOS apps...

YOLO: Bullet Paced Algorithm – popular choice for object detection in autonomous vehicles 

According to world health organization, more than 1.35 million...

How to Determine Whether a Component Is Present in ViewPort

Hi guys, in this article we will learn about how to check the position of a component in the viewport, i.e., the viewable area...

Best Practices for React State Management

React state management is a crucial aspect of building scalable and maintainable applications with React. State management helps in keeping track of data that...

Error Handling in React Js

Errors are bound to happen in our applications, whether they’re server-related errors, edge cases, api calling issues or others. As such, many methods have...

LEAVE A REPLY

Please enter your comment!
Please enter your name here