Zustand
Using Zustand for simple global state management in client components.
Optional Feature
Zustand is not included by default to keep the core lean. Install it if you specifically need global client state.
Zustand: Simple Global State Management
Zustand is a small, fast, and scalable state-management solution using simplified flux principles. It's often compared to Redux but with much less boilerplate, feeling closer to using React's useState
hook.
Often Not Required
In many Next.js applications you even might no need zustand. Server Components handle initial data very well, Server Actions handle mutations, and props can be passed down. Consider Zustand primarily when you need to share client-side state across multiple, unrelated components without excessive prop drilling.
Setup
Let's set up Zustand step by step:
1. Installation
2. Create a Task Store
Create a hook for managing shared application state. This example manages a list of tasks and a delete permission flag.
Usage Example: Managing Tasks and Permissions
This component demonstrates initializing the store with data from props, updating task state, and managing a separate permission flag.
How It Works
- Store Creation: A central store (
useTaskStore
defined inhooks/use-global-state.ts
) holds shared state (tasks
,canDelete
) and actions (initializeTasks
,toggleTask
,toggleDeletePermission
). - Initialization: The
TaskDisplay
component receivesinitialTasks
via props and callsinitializeTasks
inside auseEffect
hook (running once on mount) to populate the store's task list. - State Updates: User interactions (clicking checkboxes or the permission button) call actions (
toggleTask
,toggleDeletePermission
) which update the state in the central store. - Reactivity: Zustand ensures that
TaskDisplay
(and any other component usinguseTaskStore
) re-renders automatically when the parts of the state it subscribes to (tasks
,canDelete
) change.