📦

Best Practices for Zustand in React

Mar 26, 2025

Lecture Notes: Best Practices for Using Zustand in React

Introduction to Zustand

  • Zustand is a state manager for React applications.
  • Simple to start with and unopinionated.
  • Enhances applications with middleware.
  • Very lightweight (~1 kilobyte in bundle size).

Getting Started with Zustand

  • Creating a Hook:
    • Use the create function from Zustand to set up a store.
    • Define initial state (e.g., an empty to-do array, a isSubscribed boolean).
  • Updating State:
    • Use an action to update state immutably.
    • Shared state can be accessed by any component without prop drilling or context.

Best Practices in Zustand

Use Custom Hooks

  • Export custom hooks rather than direct store hooks.
  • Encapsulate selector logic in hooks for better maintainability.
  • Helps avoid unintentional subscriptions to the entire store.

Avoid Rendering on Unchanged State

  • Direct state access from the store can trigger unnecessary re-renders.
  • Use atomic stable selectors to prevent re-renders when unrelated state changes.

Avoid Object Selectors

  • Constructing object selectors can cause unnecessary renders.
  • Object selectors fail strict equality checks due to new object creation.
  • Prefer atomic selectors or use shallow for shallow comparison if needed.

Separate Actions from State

  • Actions modify state and should be separated for clarity.
  • Use a single actions object to hold all functions.
  • This approach keeps actions referentially stable and minimizes unnecessary renders.

Model Actions as Events

  • Actions should encapsulate business logic instead of being simple setters.
  • Examples: addTodo, removeTodo, toggleIsSubscribed.

Organizing Your Stores

  • Create focused stores for different parts of the application.
  • Consider creating separate stores or slices to keep the application organized.
  • Avoid storing unrelated state variables in the same store.

Middleware and Additional Tools

  • Middleware Options:
    • immer: Helps with cleaner destructuring.
    • persist: Sets up local storage automatically.
    • devtools: Integrates Zustand with Redux Dev Tools.

Final Tips

  • Consider organizing the application with multiple small stores.
  • Explore middleware options for enhanced functionality.

Conclusion

  • Zustand keeps state management simple and maintainable.
  • Encourages modular and organized code structures.
  • Invite comments and suggestions from the community for further best practice ideas.