Skip to main content

Front-End Development

Redux vs Zustand: A Quick Comparison

Graphic Designers At Work.

Imagine you’re in a library. Redux is like a huge, well-organized library where every book is perfectly categorized, labeled, and placed in its specific spot. It’s ideal for a massive collection, but getting everything in order can take a lot of time. Zustand, on the other hand, is like a comfy reading corner with just a few handpicked books. Everything is right at your fingertips, and you don’t have to spend time organizing it; pick up what you need and enjoy.

In this blog, we’ll explore Redux and Zustand to help you decide which is the perfect fit for your project, whether you’re managing a huge amount of state or just need a few key pieces.

In a previous blog, I explored the essential factors to keep in mind when picking a state management library. Now, let’s take a closer look at what makes Redux and Zustand stand out in this decision-making process.

Reduxvsxustand

Each library, whether it’s Redux or Zustand, has its own challenges. Let’s discuss the downsides!

Redux:

  • Challenging for Beginners: Mastering Redux can be tough for newcomers due to its complex concepts like reducers and middleware.
  • Code Bloat: Expect lots of boilerplate code, especially for simpler tasks, which can slow down the development process.
  • Too Complex for Small Apps: Redux can be over-engineered for smaller projects, adding unnecessary complexity and extra code.

Zustand:

  • Limited Middleware: No built-in tools for side effects like Redux, so you need to set it up yourself.
  • Smaller Community: Fewer resources and tutorials compared to Redux.
  • Not for Complex State: Not the best for very large or complex state management.

Implementing with Code

Let’s dive into some code examples to showcase how Redux and Zustand work in action.

Redux:

Install the packages of Redux by executing the command below:

npm install @reduxjs/toolkit react-redux

Example –

Let’s create a simple counter application using Redux for state management within a React application. Here’s how we can implement it step by step:

Action.js:

export const increment = () => ({ type: 'INCREMENT' });
export const decrement = () => ({ type: 'DECREMENT' });

reducer.js

const counterReducer = (state = 0, action) => {
    switch (action.type) {
      case 'INCREMENT':
        return state + 1;
      case 'DECREMENT':
        return state - 1;
      default:
        return state;
    }
  };
  
  export default counterReducer;

Store.js

import { configureStore } from '@reduxjs/toolkit';
import counterReducer from './reducer';

// Create Redux store using configureStore
const store = configureStore({
  reducer: counterReducer
});

export default store;

App.js

import React from 'react';
import { useDispatch, useSelector } from 'react-redux';
import { increment, decrement } from './actions';

function App() {
  const count = useSelector((state) => state); // Access state from Redux store
  const dispatch = useDispatch();

  return (
    <div style={{ textAlign: 'center' }}>
      <h1>{count}</h1>
      <button onClick={() => dispatch(increment())}>+</button>
      <button onClick={() => dispatch(decrement())}>-</button>
    </div>
  );
}

export default App;

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './App';
import store from './store'; // Import the store

// Wrap your app with Provider and pass the Redux store
ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
);

Key Redux Concepts:

  • Centralized State: Redux stores the entire application state in a single, immutable store, providing a consistent state across the app.
  • Actions & Reducers: Actions are dispatched to signal state changes. Reducers respond by updating the state based on these actions in a pure, predictable manner.
  • Boilerplate Code: Redux often involves a significant amount of boilerplate, requiring explicit definitions for actions, reducers, and the store setup.
  • React Integration: The react-redux library is used to connect React components to the Redux store, enabling state access and updates via useSelector and useDispatch hooks or connect function.

Zustand:

To install Zustand –

npm install Zustand

 

Example –

Store.js

import { create } from 'zustand';

const useStore = create((set) => ({
  count: 0,
  increment: () => set((state) => ({ count: state.count + 1 })),
  decrement: () => set((state) => ({ count: state.count - 1 }))
}));

export default useStore;


App.js

// App.js (React Component)
import React from 'react';
import useStore from './store';  // Import the Zustand store

function App() {
  // Accessing the state and actions from Zustand store
  const { count, increment, decrement } = useStore();

  return (
    <div>
      <h1>{count}</h1>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
    </div>
  );
}

export default App;

index.js

// index.js (React entry point)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';  // Import the App component

// Rendering the App component into the DOM
ReactDOM.render(
  <App />,
  document.getElementById('root')
);

Key Zustand Concepts:

  • Minimal Setup: Create a store with a single create() function.
  • Direct State Manipulation: State is mutated directly in the store, without actions or reducers.
  • No Boilerplate: Simple, intuitive API with minimal setup.
  • React Integration: Use the useStore hook to access state and actions in components.

 Choosing between Redux and Zustand –

Picking between Redux and Zustand is like choosing between a powerful engine and a smooth ride. Redux offers a ton of features, making it perfect for big, complex applications, but it requires time and effort to learn. Zustand, on the other hand, is the go-to for quick, simple projects, giving you fast setup and ease of use with minimal fuss. Need power and customization? Redux is your choice. Want speed and simplicity? Go with Zustand. Whether you need to build something scalable or just get the job done fast.

In my opinion, the key is understanding your project’s needs. Once you do, you can choose the right tool for smooth development and easy state management.

Pick wisely according to what aligns best with your workflow! That’s it for today, but don’t worry; more posts on state management libraries are coming soon to help you level up your projects. Until then, keep experimenting, and happy coding!

Leave a Reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Muskan Sheikh

Muskan Sheikh is a UI developer at Perficient, specializing in React and Drupal projects. With a strong passion for front-end development, she consistently strives to create intuitive and user-friendly interfaces. Muskan is driven by a deep curiosity to explore new technologies and is always seeking opportunities to enhance her technical expertise.

More from this Author

Follow Us