Posts

Zustand
2024

How to manage a User profile state with Zustand, Typescript and React.

Zustand

Zustand is a small, fast and scalable bearbones state-management solution. It has a simple API based on hooks, without boilerplate or opinionated patterns.

1import { create } from 'zustand'
2
3interface UserState {
4  user: {
5    name: string
6    email: string
7    avatar: string
8  } | null
9  setUser: (user: UserState['user']) => void
10  clearUser: () => void
11}
12
13const useUserStore = create<UserState>((set) => ({
14  user: null,
15  setUser: (user) => set({ user }),
16  clearUser: () => set({ user: null }),
17}))
18
19// Usage in component
20function Profile() {
21  const { user, setUser, clearUser } = useUserStore()
22
23  return (
24    <div>
25      {user ? (
26        <div>
27          <p>Welcome, {user.name}!</p>
28          <button onClick={clearUser}>Logout</button>
29        </div>
30      ) : (
31        <button onClick={() => setUser({
32          name: 'John',
33          email: 'john@example.com',
34          avatar: '/avatar.png'
35        })}>
36          Login
37        </button>
38      )}
39    </div>
40  )
41}

Zustand is perfect for small to medium applications where you need global state management without the complexity of Redux or other heavy solutions.