Back to roadmaps zustand Course

Debugging with Devtools and Subscriptions

As your web application grows, tracking state mutations can become difficult. Let us configure the DevTools debugging panel and explore subscribing to state changes from outside of React components.


1. Connecting Redux DevTools (devtools)

Zustand integrates directly with the popular Redux DevTools Chrome Extension. This allows you to inspect state history, track individual actions, and travel backward in time to revert state changes.

Import and wrap your store initializer with devtools:

import { create } from "zustand";
import { devtools } from "zustand/middleware";

interface AuthState {
  isLoggedIn: boolean;
  login: () => void;
}

export const useAuthStore = create<AuthState>()(
  devtools(
    (set) => ({
      isLoggedIn: false,
      login: () => set({ isLoggedIn: true }, false, "auth/login"),
    }),
    {
      name: "AuthenticationStore", // Custom store identifier in DevTools
    }
  )
);

The third argument in the set function (such as "auth/login") registers a label for the action in the DevTools log window.


2. Listening to State Updates (subscribe)

Sometimes you need to monitor state changes or trigger side effects from outside React components (for example, logging analytical actions or modifying Axios authorization header values).

You can achieve this using the store .subscribe method:

import { useAuthStore } from "./stores/useAuthStore";

// Subscribe to all updates in the authentication store
const unsubscribe = useAuthStore.subscribe((state, previousState) => {
  console.log("State updated from:", previousState.isLoggedIn, "to:", state.isLoggedIn);
  
  if (state.isLoggedIn) {
    // Perform analytics track
  }
});

// To stop listening, call the returned function
// unsubscribe();

3. Subscribing to Specific Slices

To prevent the subscriber function from executing on every store change, use transient selector selectors:

// Subscribe only to changes in isLoggedIn, ignoring other keys
const unsubscribe = useAuthStore.subscribe(
  (state) => state.isLoggedIn,
  (isLoggedIn) => {
    console.log("Logged in status changed:", isLoggedIn);
  }
);
Published on Last updated: