Hello! Welcome to the next lesson in our module on Advanced State Management.
In our last lesson, we explored the core principles of Zustand. We learned that it offers a simple, powerful way to manage global client state without the boilerplate of context providers, using a hooks-based API and performance-optimized selectors.
Today, we'll move from theory to practice. Our goal is to manage global client state in an application using Zustand. We will install it, create typed stores for different parts of our application state, connect them to our components, and perform state updates, including managing complex data like arrays. This lesson will solidify your understanding of how to use Zustand effectively in a real-world, TypeScript-based React project.
1. Creating Your First Typed Store
Let's begin by setting up a basic store. This process involves three main steps: installing the library, defining the store's type signature, and implementing the store's state and actions.
You'll need to add Zustand to your project first. Open your terminal in your project directory and run:
npm install zustand
Now, let's create a store to manage user information. It's a common practice to create a store.ts file (or a stores directory) to house your state management logic.
React State Management with Zustand & TypeScript
The following video by Anson provides a clear, step-by-step guide to creating your first store with TypeScript. It covers defining the interface and implementing the store with its initial state and actions.
Watch from 02:18 to 13:54. As you watch, pay close attention to: Defining the UserStore interface to enforce type safety. Using the create<UserStore>() function, including the generic type argument. The structure of the object returned by the create callback, containing both state (username, email) and actions (setUsername, setEmail). How the set function is used within actions to update the state.
Let's break down the key pattern from the video.
Step 1: Define the Interface
First, you define the "shape" of your store with a TypeScript interface. This includes both the data (state) and the functions that will modify it (actions).
// In a file like `src/stores/userStore.ts`
interface UserState {
username: string;
email: string;
setUsername: (username: string) => void;
setEmail: (email: string) => void;
}
Step 2: Create the Store
Next, you use the create function from Zustand to bring your store to life. The create function is a generic, and we pass our interface to it to get full type safety.
import { create } from 'zustand';
// assuming UserState is defined above
export const useUserStore = create<UserState>((set) => ({
// Initial state
username: '',
email: '',
// Actions
setUsername: (newUsername) => set({ username: newUsername }),
setEmail: (newEmail) => set({ email: newEmail }),
}));
Notice that set({ username: newUsername }) doesn't require you to spread the rest of the state (...state). Zustand's set function performs a shallow merge by default, which is a convenient feature. If your new state depends on the previous state, you should use the functional update form, as we saw in the last lesson: set((state) => ({ count: state.count + 1 })).
For an official reference on this pattern, the Zustand documentation provides a concise guide.
Beginner TypeScript Guide - Zustand
The official Zustand documentation has a page dedicated to TypeScript. It's a great reference to have.
Read the section titled 'Creating a Store with State & Actions'. It shows a similar pattern for a 'Bear' store and reinforces the concept of using a TypeScript interface to define the store's shape.
2. Using the Store in Components
With our useUserStore hook created, we can now use it in any component to read state or call actions. A key principle for performance is to use selectors to subscribe components only to the specific pieces of state they need.
React State Management with Zustand & TypeScript
Let's continue with the video to see how to connect components to the store. This segment demonstrates both reading state for display and calling actions from a form to update that state.
Watch from 13:54 to 19:43. Observe: How the store is used in two different components (App and UpdateUserForm). The use of selector functions like (state) => state.username to get specific values. How state updates in one component (the form) automatically trigger re-renders in another component that is subscribed to that same piece of state.
This demonstrates one of Zustand's main advantages: you can have two sibling components share and update state without any prop drilling or context providers. The state lives in the global store, and any component can tap into it.
Example: Reading State
import { useUserStore } from './stores/userStore';
function UserProfile() {
// This component will only re-render if `username` or `email` changes.
const username = useUserStore((state) => state.username);
const email = useUserStore((state) => state.email);
return (
<div>
<p>Username: {username}</p>
<p>Email: {email}</p>
</div>
);
}
Example: Calling Actions
import { useUserStore } from './stores/userStore';
import React from 'react';
function UserSettings() {
// It's often cleaner to select the action function directly.
const setUsername = useUserStore((state) => state.setUsername);
const handleUsernameChange = (e: React.ChangeEvent<HTMLInputElement>) => {
setUsername(e.target.value);
};
return (
<input
type="text"
onChange={handleUsernameChange}
placeholder="New username"
/>
);
}
Test your understanding!
Imagine you have a store that manages a list of selected item IDs.
interface SelectionState {
selectedIds: string[];
toggleId: (id: string) => void;
}
You have two components: SelectionCount, which displays the number of selected items, and ItemList, which displays a list of items, each with a checkbox to select/deselect it.
To maximize performance, what selector would you use in the SelectionCount component?
Show answer
The most optimal selector for SelectionCount would be:
const selectionCount = useStore((state) => state.selectedIds.length);
This selector subscribes the component only to the length of the selectedIds array. The component will re-render only when an item is added or removed, but not when the array is re-ordered or an item's value changes internally (if it were an array of objects). Selecting the entire selectedIds array would be less performant, as it would cause a re-render anytime the array reference changes, even if its length remains the same.
3. Structuring State for an Application
A small application might be fine with a single store, but as it grows, you'll manage different, unrelated domains of state (e.g., user authentication, UI state, data from a form). A best practice is to split your state into multiple, domain-specific stores. This keeps your logic modular and easier to maintain.
Let's say in addition to our user store, we also want to manage a list of blog posts. Instead of adding posts, addPost, removePost, etc., to our useUserStore, we can create a separate usePostStore.
React State Management with Zustand & TypeScript
The video we've been watching discusses this exact architectural choice. It then demonstrates how to implement the 'multiple stores' pattern and use it to manage a more complex piece of state: an array of objects.
Watch the segment from 33:11 to 55:16. This is a longer, dense section, so focus on these key concepts: The decision to create a separate usePostStore instead of adding 'slices' to the user store (33:11). The implementation of the usePostStore, which manages a posts array. The patterns for immutable updates within the actions: using the spread syntax [...state.posts, newPost] for adding, and state.posts.filter(...) for removing. These should be familiar patterns from your JavaScript experience, now applied within Zustand actions.
This approach of creating multiple independent stores is explicitly endorsed by the Zustand documentation as a clean way to keep state isolated.
userStore.ts
import { create } from 'zustand';
interface UserState { /* ... as before ... */ }
export const useUserStore = create<UserState>((set) => ({ /* ... */ }));
postStore.ts
import { create } from 'zustand';
interface Post {
id: string;
title: string;
content: string;
}
interface PostState {
posts: Post[];
addPost: (post: Omit<Post, 'id'>) => void;
removePost: (id: string) => void;
}
export const usePostStore = create<PostState>((set) => ({
posts: [],
addPost: (newPost) => set((state) => ({
posts: [
...state.posts,
{ ...newPost, id: new Date().toISOString() } // Generate ID here for simplicity
]
})),
removePost: (idToRemove) => set((state) => ({
posts: state.posts.filter((post) => post.id !== idToRemove)
})),
}));
In your components, you simply import the hook for the store you need:
import { useUserStore } from './stores/userStore';
import { usePostStore } from './stores/postStore';
function Dashboard() {
const username = useUserStore((state) => state.username);
const posts = usePostStore((state) => state.posts);
// ... render UI using username and posts
}
4. Developer Experience: Debugging and Best Practices
As a professional developer, you know that maintainability and debuggability are crucial. Zustand has excellent support for the Redux DevTools, a browser extension that lets you inspect your state, view action history, and time-travel through state changes.
The video you watched briefly demonstrates setting this up, as well as using the immer middleware for simpler immutable updates.
React State Management with Zustand & TypeScript
For a quick look at how to integrate these developer tools, let's refer back to our video guide.
Watch the section on Redux DevTools (19:43 - 23:37) and the Immer middleware (55:16 - 1:04:14). You don't need to memorize the implementation, but understand what each tool offers.
- Redux DevTools: Invaluable for debugging. You wrap your store creation with the
devtoolsmiddleware. - Immer: Allows you to write code that looks mutable (e.g.,
state.posts.push(newPost)) while it handles the immutable update under the hood. This can simplify complex state updates.
Finally, having a set of clear rules can prevent common mistakes.
zustand-state-management - Claude Skills
This 'Claude Skills' guide provides an excellent cheat sheet of 'Always Do' and 'Never Do' rules when working with Zustand.
Read the sections 'Critical Rules' and 'Known Issues Prevention'. These sections are packed with practical advice that can save you significant debugging time, covering topics like TypeScript syntax, selector usage to prevent infinite renders, and more.
Conclusion
In this lesson, we put Zustand into action. You've learned how to create, type, and structure stores for a scalable React application. We saw how to connect components, perform immutable updates on complex data types like arrays, and organize state into logical, domain-specific stores.
Key Takeaways:
- Typed Stores: Always define a TypeScript interface for your store's shape and use
create<MyState>()for type safety. - Selectors are Key: Use granular selectors
(state => state.value)in components to prevent unnecessary re-renders. - Immutable Updates: Actions use the
setfunction to perform immutable updates, often using patterns like the spread operator (...) or array methods likefilterandmap. - Multiple Stores: For a scalable application, splitting state into multiple, domain-specific stores (e.g.,
useUserStore,usePostStore) is a clean and maintainable pattern. - Developer Tooling: Leverage middleware like
devtoolsfor debugging andimmerfor simplified immutable logic.
Preview of the Next Lesson:
We have now covered a powerful tool for managing global client state. But what about the other major category of state we identified: server state? In our next lesson, we will introduce the core principles of a server state library like TanStack Query (React Query). You will learn why libraries like this are the modern standard for managing data fetching, caching, and synchronization with a backend.