Zustand vs Redux

What is Zustand

Zustand is one of the state management library for React. It is a simple and powerful way to manage state in React.

Why Zustand is better than Redux?

- Redux is Compilcated for beginners.

- We have to write more code for even small UI changes in Redux.

- Too much boilerplate code in Redux.

- It's easy to handle multiple store from multiple folders.

- Easier to setup and maintain than Redux.


Let me show you sample code for Redux and Zustand for a simple counter app.

Redux

First we'll setup a store and provider.

import { configureStore } from '@reduxjs/toolkit'
import counterReducer from '../features/counter/counterSlice'

export const store = configureStore({
  reducer: {
    counter: counterReducer,
  },
})

export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch

And in our index.tsx file we'll use the provider.

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

ReactDOM.render(
  <Provider store={store}>
    <App />
  </Provider>,
  document.getElementById('root')
)

Now We will create a slice to manage the state of counter.

counterSlice.ts

import { createSlice, PayloadAction } from '@reduxjs/toolkit'

export interface CounterState {
  value: number
}

const initialState: CounterState = {
  value: 0,
}

export const counterSlice = createSlice({
  name: 'counter',
  initialState,
  reducers: {
    increment: (state) => {
      state.value += 1
    },
    decrement: (state) => {
      state.value -= 1
    },
  },
})

export const { increment, decrement } = counterSlice.actions
export default counterSlice.reducer

Zustand

In Zustand we just need to create a store and set the state values.

import create from 'zustand'

interface ValueState {
  bears: number
  increment: (by: number) => void
  decrement: (by: number) => void
}

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

The main advantage of Zustand is that we can use multiple stores in one app. And we don't even need wrap the whole app with provider. We can just use the store in our components.

I have just finished my exams and stated to work on my blog again. I will try to keep up with the progress. I hope you will like it. Let me know! I'm always open to feedback.