DEV Community

Cover image for Redux toolkit : simplified
Dipak Kumar
Dipak Kumar

Posted on

Redux toolkit : simplified

Definition
Redux is a predictable state management library. It basically allows you to store JS variables in a global object that can be accessed and modified from any JS file (or component).

You can use redux with vanilla JS or any JS framework like React, Angular, Vue, NextJS, etc. In this article, I have used redux-toolkit with react but the core concepts remain the same.

Redux -> Redux toolkit?
Redux is probably the most hated tool since it requires you to write a lot of boiler code to set up redux in your react app. To fix this redux team came up with a modern approach to redux called the redux toolkit. The redux toolkit is the recommended way to use redux. This new way of writing redux is clean and provides additional features. This article will help you understand the data flow in react with redux-toolkit (redux) and integrate redux in your app easily.

What are the benefits of having a state management tool?

  1. Makes the application predictable.
  2. Solve the issue of prop drilling.
  3. Makes the state flow easy to test and debug.
  4. Most importantly, a good understanding of redux is a must if you wish to clear any frontend interview.

Three core concepts of redux:
1. action creator: a function that returns an object that has at least one property called "type" and an optional property called payload. For example:

function add(){
   return{
     type: "ADD",
     payload: 2
   }
}
Enter fullscreen mode Exit fullscreen mode

2. store:

The state of your entire application is stored in one big object called the store. Simply, it keeps all the variables and their values that is being used by multiple components.

*3. reducer: *

Reducers are pure function that takes "previous state" and "actions" as parameter and it update the store based on the action type.

const reducer = (state = 0, action) => {

if (action.type == "ADD") {

return state + 1;

}

else(action.type == "SUBTRACT"){
  retrun state -1;
}
Enter fullscreen mode Exit fullscreen mode

React-Redux:
Redux is not specially design for any particular framwork, it work with all the JS framwork. To use redux in a react app, we use react-redux liberary which is an official binding app.

The only way to update the state is triggering an action. To trigger an action we use useDispatch() method provided by react-redux.

Redux installation way:

Let revisit the key takeaways:

whenever we want to update any value in the store, we dispatch the respective action.

Based on the dispatched action type, reducer update the state. Reducer perform a deep copy of previous state to avoid overwriting the other properties of original state.

Every time state update, it re-render the components that are using that property? or the entire application? or only the component that is having useSelector?

For middlewares, redux provide applyMiddlewares?

Top comments (0)