Introduction To Redux Toolkit

26 / Aug / 2022 by gaurav.rawat 0 comments

What is Redux ToolKit?

Redux Toolkit (also known as “RTK” for short) is the recommended approach for writing the Redux logic. The @reduxjs/toolkit package wraps around the core redux package, and it contains API methods and common dependencies that are essential for building a Redux app.

The Redux Toolkit package is intended to be the standard way to write Redux logic

RTK follows the ducks pattern and combines reducers, actions, and constants in one file called a slice. Each slice will provide an initial state and a reducer function for an object in the store

Redux Toolkit comes pre-bundled with below features:

  • immer.js : a library/tool to handle immutability in stores.
  • redux : For state management
  • Redux-thunk : For async calls
  • reselect :  For selecting a slice out of global store
  • automatic support for Redux Dev-tools Extension

 

Installation:

# NPM

npm install @reduxjs/toolkit

# Yarn

yarn add @reduxjs/toolkit

 

Reason for using Redux toolkit:

  • A lot lesser boilerplate code is required compared to Redux.
  • No need to set up thunk manually as redux-toolkit comes with out of box createAsyncThunk which can perform async operations.
  • Mutability might be considered an advantage or disadvantage, but if you’re not too used to writing with spread operators, you might love this feature as well. Do straight assignments and let the redux toolkit take care of mutability under the hoods.
  • current can be used to log your state anywhere in case you want to debug and understand where things are going wrong.

 

An example of what a slice looks like:

Redux Toolkit Slice in Action

As it is visible we have the reducer, and actions all in one place. One interesting thing to note is that we are directly updating the state. You might think that is it not the redux best practice to not mutate the state. Well, the answer is yes but you do not need to do that yourself. Redux Toolkit contains a library named immer.js which handles it for you internally.

FOUND THIS USEFUL? SHARE IT

Leave a Reply

Your email address will not be published. Required fields are marked *