Open In App

Why Redux Toolkit is preferred over Redux ?

While working as a Front-end Developer or Full Stack Developer, many engineers encountered Redux. But Recently Redux Team launched Redux Toolkit(RTK), an officially recommended 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. It is recommended by the Redux Developers Team.

Redux:

Redux is a state management tool that makes it easier to pass data between components. Redux provides a store which makes the state inside components easier to maintain. Along with stores, react-redux introduces actions and reducers which work simultaneously with stores to make the state more predictable



Redux ToolKit(RTK):

Redux Toolkit is used for writing redux code but in a more concise way. Redux Toolkit (RTK) solves problems that most of the developer’s face who used redux in a react application. RTK abstracts the basic redux code and provides us boilerplates that enable us to write redux code in less lines of code

Issues with basic Redux:

Reasons for preferring RTK(Redux ToolKit):

Dependencies Included with RTK(Redux ToolKit):

To install RTK(Redux ToolKit) in the existing project use the command

# NPM
npm install @reduxjs/toolkit

# Yarn
yarn add @reduxjs/toolkit

To create a new project with RTK use the command:

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

Important features provided with RTK:

Comparison Between Redux and Redux Toolkit in React:

Comparing Store and Reducers




// Redux
const addHandler=(state=0,action)=>{
if(action.type==='ADD')
{
    return state+1;
}
return state;
}
  
const store = createStore(addHandler);
  
store.dispatch({type:'ADD'});




// Resux Toolkit
// Action Creators
const add = createAction('ADD'); 
  
const addHandler = createReducer(0, {  
  [add]: state => state + 1
})
  
const store = configureStore({
  reducer: addHandler
})
  
store.dispatch(add());

Comparing Redux DevTools Extension:






// Redux
const store = createStore(
  reducer,   window.__REDUX_DEVTOOLS_EXTENSION__ && 
             window.__REDUX_DEVTOOLS_EXTENSION__()
);




// Reduc Toolkit
const store = configureStore(
  reducer:rootReducer );

Comparing modification of states:




// Redux
const initialState={
counter:0}
  
const handler=(state=initialState,action){
return{
    ...state,
    counter:state.counter+1;
    }    
}




// Redux Toolkit
const initialState={
counter:0}
  
const handler=(state=initialState,action){
return{
    counter:state.counter+1;
    }    
}

Conclusion:


Article Tags :