0
0
NextJSframework~5 mins

Zustand for client state in NextJS

Choose your learning style9 modes available
Introduction

Zustand helps you keep track of data that changes in your app. It makes sharing and updating this data easy and fast.

You want to share data between different parts of your app without passing props everywhere.
You need a simple way to update and read data that changes often, like user clicks or form inputs.
You want to avoid complex setups but still have a powerful state management tool.
You want your app to feel fast by updating only what needs to change.
You want to keep your code clean and easy to understand.
Syntax
NextJS
import { create } from 'zustand'

const useStore = create(set => ({
  count: 0,
  increase: () => set(state => ({ count: state.count + 1 })),
  decrease: () => set(state => ({ count: state.count - 1 }))
}))

create makes a store to hold your data and actions.

The function inside create gets set to update the state.

Examples
This store holds a name and a function to change it.
NextJS
const useStore = create(set => ({
  name: 'Guest',
  setName: (newName) => set({ name: newName })
}))
This store manages a list of tasks and adds new ones.
NextJS
const useStore = create(set => ({
  todos: [],
  addTodo: (todo) => set(state => ({ todos: [...state.todos, todo] }))
}))
Sample Program

This React component uses Zustand to keep a number that can go up or down. Buttons update the number, and the screen shows the current count.

It uses simple buttons with labels for accessibility and inline styles for spacing and size.

NextJS
import React from 'react'
import { create } from 'zustand'

const useStore = create(set => ({
  count: 0,
  increase: () => set(state => ({ count: state.count + 1 })),
  decrease: () => set(state => ({ count: state.count - 1 }))
}))

export default function Counter() {
  const { count, increase, decrease } = useStore()

  return (
    <main style={{ fontFamily: 'Arial, sans-serif', padding: '1rem' }}>
      <h1>Counter: {count}</h1>
      <button aria-label="Decrease count" onClick={decrease} style={{ marginRight: '1rem', fontSize: '1.25rem' }}>-</button>
      <button aria-label="Increase count" onClick={increase} style={{ fontSize: '1.25rem' }}>+</button>
    </main>
  )
}
OutputSuccess
Important Notes

Zustand stores are very lightweight and easy to use.

Always use the store hook inside React components to keep UI in sync.

Use clear names for your state and actions to keep code readable.

Summary

Zustand helps manage changing data simply and clearly.

It works well for sharing state across many parts of your app.

Using Zustand keeps your code clean and your app fast.