Industry Insights 5 Zustand: A Lightweight State Management Library for React

Industry Insights

sonatafy-glyph

Zustand: A Lightweight State Management Library for React

by | Oct 21, 2024 | All, Programming, Software Development

About The Author Alejandro Ramírez

Alejandro Ramirez is a Director of Engineering with over 20 years of experience in Software Development, across a diverse range of industries and applications.

Zustand is a highly performant and flexible state management library for React applications. It allows developers to create state stores easily without complex setups or patterns. Zustand uses an intuitive API, making it a great choice for managing both local and global state in React projects, no matter the size.

 

Advantages of Using Zustand

  • Minimal Boilerplate: Zustand requires minimal setup compared to libraries like Redux. You can create and modify a state store with just a few lines of code.
  • Performance: It’s optimized to prevent unnecessary re-renders, ensuring components only re-render when their state changes.
  • Flexible: Zustand is extremely flexible, allowing multiple stores and supporting synchronous and asynchronous actions without the need for middleware.
  • Devtools Support: It integrates with Redux DevTools, making debugging and inspecting state changes during development seamless.
  • Lightweight: Zustand is a small library (~1KB gzipped), ensuring it doesn’t bloat your application.

Zustand vs Redux: Key Differences

  • Boilerplate:
    • Redux: Requires setting up actions, reducers, and middleware, leading to boilerplate-heavy setups.
    • Zustand: Allows direct state manipulation with almost no boilerplate. You can modify state directly inside the store.
  • State Management:
    • Redux: Uses a single centralized store with strict patterns (actions, reducers).
    • Zustand: Provides a more flexible, store-based state management approach, allowing multiple independent stores and more freedom in structure.
  • Middleware:
    • Redux: Relies heavily on middleware like Redux Thunk or Saga for side effects (async operations).
    • Zustand: Supports async actions out of the box with JavaScript’s native async/await or promises without additional libraries.
  • Learning Curve:
    • Redux: Has a steeper learning curve due to its strict architecture and pattern requirements.
    • Zustand: Simpler to learn with a natural API similar to JavaScript, making it easy for developers to pick up.

 

Variable Fonts- A Technical Deep Dive for Developers - v2

Example Project: Todo List Using Zustand in TypeScript

1. Install Zustand:

npm install zustand

2. Create the Store (TypeScript):

import { create } from 'zustand';

interface Todo {
  id: number;
  text: string;
}

interface TodoStore {
  todos: Todo[];
  addTodo: (todo: Todo) => void;
  removeTodo: (id: number) => void;
}

export const useTodoStore = create((set) => ({
  todos: [],
  addTodo: (todo) =>
    set((state) => ({
      todos: [...state.todos, todo],
    })),
  removeTodo: (id) =>
    set((state) => ({
      todos: state.todos.filter((todo) => todo.id !== id),
    })),
}));

3. Create the TodoList Component (TypeScript):

import React, { useState } from 'react';
import { useTodoStore } from './todoStore';

function TodoList() {
  const todos = useTodoStore((state) => state.todos);
  const addTodo = useTodoStore((state) => state.addTodo);
  const removeTodo = useTodoStore((state) => state.removeTodo);
  const [inputValue, setInputValue] = useState('');

  const handleAddTodo = () => {
    addTodo({ id: Date.now(), text: inputValue });
    setInputValue('');
  };

  return (
    

Todo List

setInputValue(e.target.value)} />
    {todos.map((todo) => (
  • {todo.text}
  • ))}
); } export default TodoList;

The Conclusion

Zustand offers a lightweight, flexible alternative to Redux for managing state in React applications. With its minimal setup and highly optimized performance, Zustand fits perfectly into both small and large-scale applications.