DEV Community

Cover image for What is Zustand? How to Use in React || React Native
Hesam
Hesam

Posted on

What is Zustand? How to Use in React || React Native

A small, fast and scalable state-management solution using simplified flux principles. Has a comfy api based on hooks

  • small
    Zustand is one of the smallest state management libraries with a bundle size of just 1.13kb.

  • fast
    Zustand is fast, thanks to its small size, making us have instantaneous UI updates on changes to our state.

  • scalable
    With Zustand, we can create a store, which is a central point of truth where all our global app state resides in. Our store is simply a hook, which we can easily import and use where needed. making Zustand very scalable.

Zustand

Let's go over a basic store example with Zustand using Typescript.

Step 0: Install zustand

yarn add zustand
Enter fullscreen mode Exit fullscreen mode

Step 1: Import and Create your Store (ex: Authentication)

// authStore.ts
import create from 'zustand';
import getToken from './utils';

interface AuthStateType {
  status: 'idle' | 'signOut' | 'signIn';
  token: string | null;

  signIn: (token: string) => void;
  signOut: () => void;
  hydrate: () => void;
}


export const useAuth = create<AuthStateType>((set, get) => ({
  status: 'idle',
  token: null,

  signIn: token => {
    set({ status: 'signIn', token: token });
  },

  signOut: () => {
    set({ status: 'signOut', token: null });
  },

  hydrate: () => {
      const token = getToken();

      if (token !== null) {
        get().signIn(token);
      } else {
        get().signOut();
      }
  },
}));
Enter fullscreen mode Exit fullscreen mode

zustand+react+native+tutorial

Step 2: Use your auth store (Inside of a React Component).

  • Check status
const { status } = useAuth();
console.log(status); // idle
Enter fullscreen mode Exit fullscreen mode
  • SignIn
const { signIn, status } = useAuth();
signIn("user token");
console.log(status); // signIn
Enter fullscreen mode Exit fullscreen mode
  • SignOut
const { signOut, status } = useAuth();
signOut();
console.log(status); // signOut
Enter fullscreen mode Exit fullscreen mode
  • Hydrate
const { hydrate } = useAuth();
hydrate();
Enter fullscreen mode Exit fullscreen mode

Step 3: Use your auth store (Outside of a React Component)

// authStore.ts

export const useAuth = create<AuthState>((set, get) => ({
...
}))

// add this line
export const hydrateAuth = () => useAuth.getState().hydrate();
Enter fullscreen mode Exit fullscreen mode

now you can use hydrateAuth Outside of a React Component.

import { hydrateAuth } from "./authStore.ts"
hydrateAuth()
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
azibom profile image
Mohammad Reza

Nice article, keep it up :-)