Naukri Engineering

Think, Develop, Rollout, Repeat. The world class recruitment platform made with love in India. https://www.naukri.com/

Deep Dive: Using Redux Toolkit vs. Vanilla Redux in Real-Time Projects

--

In the world of React state management, Redux has long stood as a reliable monolith. With the introduction of Redux Toolkit, many developers have been presented with a new option that promises simplicity without compromising on power. In this deep dive, we will dissect the usage of both in real-time projects, hoping to shed light on which might be more appropriate for your needs.

Problem Statement:

Choosing between Redux Toolkit and vanilla Redux can be challenging, especially for teams embarking on new projects or those seeking to refactor existing code bases. The dilemma often revolves around balancing simplicity with control, rapid development with performance optimisation, and familiarity with innovation.

Unveiling the Pros and Cons of Redux and Redux Toolkit

1. Initialisation and Setup

Redux: Provides Granular Control. Setting up a store with Redux requires setting up actions, action types, reducers, and a store. Middleware like redux-thunk or redux-saga is often used to handle asynchronous actions. The setup can be verbose and requires a bit of boilerplate code.

Every aspect of your store, from middleware to enhancers, is explicitly defined by you. This is ideal for projects with specific requirements. Although, the initial setup can be time-consuming, especially for beginners.

Redux Toolkit: The toolkit simplifies the setup process. With configureStore, you can easily set up the store with middleware and devtools. The toolkit also bundles redux-thunk for async actions.

Fast setup. The configureStore function sets up the store with built-in best practices. Middleware like redux-thunk is included and set up out of the box. While convenient, it might abstract away too many details for those looking to learn the intricacies of Redux.

2. Boilerplate Code

Redux: One common critique of Redux is the amount of boilerplate code required. For every piece of state, developers need to define action types, action creators, and reducers.

Even though the separation of action types, action creators, and reducers can be cumbersome in large projects. These standard patterns are well-known, which makes codebases consistent and easier to understand for developers familiar with vanilla Redux.

Redux Toolkit: Redux Toolkit introduces createSlice which automatically generates action creators and action types based on the reducers you provide. This significantly reduces boilerplate.

createSlice and createAsyncThunk massively reduce boilerplate. This can make the codebase cleaner and more maintainable. For teams accustomed to vanilla Redux, there might be an initial learning curve.

3. Immutability

Redux: In Redux, the state must be treated as immutable. This means when updating the state, you often use utilities like spread operators or libraries like immutable.js.

Although explicit control over state updates ensures that developers understand state transitions, mistakes like directly mutating state are common and can lead to hard-to-debug issues.

Redux Toolkit: With the toolkit, the createSlice function allows you to write “mutating” logic, but under the hood, it uses the Immer library to ensure the state remains immutable.

Even though the toolkit allows developers to write mutation-like code, which is then safely translated to immutable updates, over-reliance on Immer might lead to gaps in understanding for those not familiar with immutable principles.

4. Middleware

Redux: By default, Redux doesn’t come bundled with middleware. Developers usually integrate middleware like redux-thunk or redux-saga for handling side effects.

Despite the fact that choosing and configuring your middleware, gives you total control over side effects and async logic. This can lead to challenges, especially for beginners trying to set up asynchronous logic.

Redux Toolkit: configureStore from the toolkit sets up middleware with sane defaults, like integrating redux-thunk by default.

Although the toolkit has simplified async action creation by introducing createAsyncThunk , and integrating redux-thunk by default. This customisation might require driving out from the default setup, which could reintroduce complexity.

5. Developer Experience and Tools

Redux: Developers often use the Redux DevTools extension for debugging their Redux applications. This requires additional setup and configuration.

Redux Toolkit: The toolkit’s configureStore function has built-in support for Redux DevTools, making debugging easier right out of the box.

6. Scaling and Performance

Redux: In spite of the fact that in large-scale projects, the granularity of vanilla Redux might offer more optimization points, developers need to be more cautious about performance, as careless patterns might slow down applications.

Redux Toolkit: Built with performance in mind, the toolkit offers tools like createEntityAdapter for optimized state access and updates. Some of these advanced optimizations might still require manual intervention.

7. Community and Ecosystem

Redux: Redux has a large community, and there are numerous libraries and middleware available. It’s tried and tested and has vast resources for learning and troubleshooting.

Even though there’s a vast community along with a wealth of resources, plugins, and solutions for nearly any challenge, the overwhelming amount of information can be confusing for newcomers.

Redux Toolkit: While newer, Redux Toolkit is the official recommendation for Redux setup. It’s rapidly gaining adoption and has the backing of the core Redux team.

Being the official recommendation means high-quality, up-to-date resources, and community support. As toolkit is still growing, so it might lack the vast ecosystem that vanilla Redux offers.

Analogical Insights: Understanding Redux and Redux Toolkit through Food Metaphors

Using Redux is like making a dal from scratch. You have granular control over every step, from defining actions to creating the store. However, it involves writing a lot of boilerplate code, which can be time-consuming and prone to errors.

// Redux - Making a dal from Scratch

// Define Actions
const addIngredient = (ingredient) => ({ type: 'ADD_INGREDIENT', payload: ingredient });
const removeIngredient = (ingredient) => ({ type: 'REMOVE_INGREDIENT', payload: ingredient });

// Reducer
const dalBlendReducer = (state = [], action) => {
switch (action.type) {
case 'ADD_INGREDIENT':
return [...state, action.payload];
case 'REMOVE_INGREDIENT':
return state.filter(item => item !== action.payload);
default:
return state;
}
};

// Store
const { createStore } = Redux;
const store = createStore(dalBlendReducer);

// Dispatch Actions
store.dispatch(addIngredient('salt'));
store.dispatch(addIngredient('red chilli'));
store.dispatch(removeIngredient('red chilli'));

// Get Current State
const currentIngredients = store.getState();

Using Redux Toolkit is like using a dal mix. It simplifies the process by providing inbuilt creation of actions and reducers. You just add water and mix (createSlice), and Redux Toolkit takes care of the rest, including measuring ingredients and ensuring they’re mixed properly (configureStore). While you may have less control over customisation compared to Redux, it’s faster, easier, and less prone to errors.

// Redux Toolkit - Using a dal Mix
import { configureStore, createSlice } from '@reduxjs/toolkit';

// Create a Slice
const dalBlendSlice = createSlice({
name: 'dal',
initialState: [],
reducers: {
addIngredient: (state, action) => [...state, action.payload],
removeIngredient: (state, action) => state.filter(item => item !== action.payload),
},
});

// Create Store
const store = configureStore({
reducer: dalBlendSlice.reducer,
});

// Dispatch Actions
store.dispatch(dalBlendSlice.actions.addIngredient('salt'));
store.dispatch(dalBlendSlice.actions.addIngredient('red chilli'));
store.dispatch(dalBlendSlice.actions.removeIngredient('red chilli'));

// Get Current State
const currentIngredients = store.getState();

Personal Experience and Use Cases

In our experience, we found Redux Toolkit to be particularly advantageous in scenarios where rapid development and ease of maintenance were paramount. For projects requiring quick iteration cycles or those with a focus on developer productivity, Redux Toolkit’s streamlined setup and reduced boilerplate significantly expedites our workflow.

However, in legacy projects where the team was deeply entrenched in traditional Redux patterns or where granular control over state management was critical for performance optimization, sticking with vanilla Redux proved beneficial. The familiarity with established patterns and the ability to fine-tune every aspect of the Redux setup allowed us to address specific project requirements effectively.

Conclusion

While both Redux and Redux Toolkit have their merits, for developers new to Redux or those looking to simplify their existing Redux codebase, the Redux Toolkit offers a streamlined and efficient approach to state management. However, if you’re working on a legacy project or have specific needs that require a more “manual” approach, vanilla Redux still stands strong.

The choice between Redux Toolkit and vanilla Redux often comes down to the project’s needs and the team’s familiarity. For new projects or those looking for simplicity without compromising power, Redux Toolkit is an excellent choice. However, for projects with specific needs or teams deeply rooted in vanilla Redux, the traditional approach still offers robust solutions.

Links to Further Resources:

  1. Redux Documentation
  2. Redux Toolkit Documentation
  3. Redux DevTools Extension
  4. Redux Thunk Middleware
  5. Immer Library

Thank you for embarking on this journey through Redux and Redux Toolkit with me. Your commitment to learning and exploring is truly appreciated. If you have any further questions or would like to discuss this topic in more detail, feel free to reach out in comment section of this blog. Let’s keep the conversation going!

--

--

Naukri Engineering
Naukri Engineering

Published in Naukri Engineering

Think, Develop, Rollout, Repeat. The world class recruitment platform made with love in India. https://www.naukri.com/

No responses yet