Supercharge Your React State Management with Zustand: A Lightweight Alternative to Redux

Supercharge Your React State Management with Zustand: A Lightweight Alternative to Redux

ยท

4 min read

Hello everyone! Today, I'd like to discuss Zustand and why it can be a preferable alternative to Redux. We'll explore how to incorporate Zustand into your project, highlighting its simplicity and ease of implementation. So, without further ado, let's get started

What is Zustand?

First, let's understand what Zustand is. Zustand is a lightweight state management library designed specifically for React. It offers a streamlined approach to managing and accessing states within your components, presenting a simpler syntax compared to Redux.

To demonstrate the power of Zustand, let's build a demo counter app with a navbar. In this example, when you click the "+" or "-" button, the counter component will reflect the changes, and the navbar will also display the updated count using Zustand. Imagine it as an e-commerce app where modifying the quantity of a product updates the cart count displayed in the navbar.

Assuming you have a basic understanding of setting up a React app with Vite, let's begin implementing this example.

Install the Zustand

# NPM
npm install zustand

# Yarn
yarn add zustand

Create a store :

  1. Create a new file called store.js in your project directory.

  2. In store.js, import the necessary functions from the Zustand library:

//store.js
import {create} from 'zustand'

export const useCounter = create((set)=>({
  counter:0,
  increment: () => set((state) => ({ counter: state.counter + 1 })),
  decrement: () => set((state) => ({ counter: state.counter - 1 })),
}))

I know you have a lot of questions related to snippets I will explain each of them.

  • Create: it s a function provided by Zustand that is used to create a store.

  • useCounter: it is the name of the store, which acts as a container for holding information and actions.

  • counter: it represents the state variable with an initial value of 0.

  • set: it is a special function given by Zustand to update the state in the react. it has an argument called state which is our current state.

  • increment is an action that updates the state by increasing the counter value by 1.

  • decrement is an action that updates the state by decreasing the counter value by 1

Set up components Nav and counter and import in the app.js file.

//App.js

import Counter from "./components/Counter";
import Nav from "./components/Nav";
import "./styles.css";

export default function App() {
  return (
    <>
      <Nav />
      <Counter />
    </>
  );
}

So what happened exactly with this snippet?

Just import two components Nav and Counter in the App.js file.

//Nav.js
import { useCounter } from "../store";
function Nav() {
  const counter = useCounter((state) => state.counter);
  return (
    <>
      <div>Counter:{counter}</div>
      <hr />
    </>
  );
}

export default Nav;

So what happened exactly with this snippet?

  • useCounter: it allows us to access the Zustand store created previously. It establishes a direct connection to the store, enabling us to read and update the data within our components.

  • '(state) => state. counter)': This is a function called a "selector" that defines what part of the store's state we want to access. In this case, it selects the counter property from the store's state.

//Counter.js
import { useCounter } from "../store";

function Counter() {
  const counter = useCounter((state) => state.counter);
  const increment = useCounter((state) => state.increment);
  const decrement = useCounter((state) => state.decrement);

  return (
    <>
      <button onClick={() => increment()}>+</button>
      <span>{counter}</span>
      <button onClick={() => decrement()}>-</button>
    </>
  );
}

export default Counter;

So what happened exactly with this snippet? some are similar to previous ones let's explain what is different

  • '(state) => state.increment)': This function is a selector that retrieves the increment action from the store's state. It allows you to access and use the increment action in your component.

  • '(state) => state.decrement)': This function is a selector that retrieves the decrementaction from the store's state. It allows you to access and use the decrementaction in your component.

  • This concludes the explanation of the differences in the Counter.js snippet

And that wraps up our blog! I hope this article has given you a clear understanding of how to get started with Zustand and its user-friendly nature, especially when compared to Redux's boilerplate code requirements. In many cases, Zustand can be a more straightforward and efficient choice. However, for more intricate projects, Redux still holds its value.

Thank you for investing your time in reading this blog. I sincerely hope that the information provided here proves helpful and empowers you on your coding journey. Wishing you a future filled with success, happiness, and enjoyable coding experiences! Happy coding! ๐Ÿ˜Š

ย