DEV Community

Cover image for Zustand 101: A Beginner's Guide to Global State Management in React
professorjrod
professorjrod

Posted on • Updated on

Zustand 101: A Beginner's Guide to Global State Management in React

If you're a React developer, you've probably heard of Redux, a popular JavaScript library for managing application state.

However, if you're looking for a simpler and more lightweight alternative, you might want to consider Zustand.

zustand bear

If you don't know already, global state management is the process of centralizing the shared state of a web application.

This helps to ensure that different parts of the application can communicate and share data with one another, and can reduce the risk of inconsistencies or bugs like prop drilling.

state diagram

Zustand is a state management library for React that is easy to use, lightweight, fast, and most importantly: it is super simple to learn! Zustand allows you to manage your application's state in a simple and intuitive way, without the need for complex reducers and action creators like Redux.

Creating a Store

The first step in using Zustand is to create a store. A store is an object that holds your application's state and provides methods for updating that state.

To create a store, you'll need to import create from Zustand. The create function takes a function that returns your initial state as an argument:

import create from 'zustand';

const useCountStore = create((set) => ({
  count: 0,
}))
Enter fullscreen mode Exit fullscreen mode

In this example, we've created a store with an initial state of { count: 0 }. Because the purpose of Zustand is to provide global state, the value of count can later be accessed in any component.

Updating State

Once you've created your store, you can update the state using the set method provided by the store. The set method takes a function that receives the current state as an argument and returns the new state:

store.set(state => ({ count: state.count + 1 }));
Enter fullscreen mode Exit fullscreen mode

It's good practice to scope these functions in your store so that they can be accessed globally. It's kind of overkill for our simple use but it's good practice.

const useCountStore = create((set) => ({
  count: 0,
  increaseCount: () => set((state) => ({ count: state.count + 1 })),
  resetCount: () => set({ count: 0 }),
}))
Enter fullscreen mode Exit fullscreen mode

Consuming State

To access the state from your React components, you'll need to use the useStore hook provided by Zustand. The useStore hook takes a function that receives the current state as an argument and returns the state values that you want to access. Here's an example of how we can display count to the screen:

import { useStore } from 'zustand';

function MyComponent() {
  const count = useStore(state => state.count);

  return <div>{count}</div>;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we've used the useStore hook to access the count value from the store and render it in a div element. Simple!

Modifying State

Modifying the state is very similar to accessing it. You will again use the useStore hook, but this time we can assign the function we want to access to a variable to use in our React component.

import { useStore } from 'zustand';

function MyComponent() {
  const count = useStore(state => state.count);
  const increaseCount = useStore(state => state.increaseCount)

  return (
    <div>
      {count}
      <button onClick={increaseCount}>Click me to increase the count!</button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Now, if you click the button, count will be increased by 1. Because the state is global, all React components accessing count will display the count + 1 when mounted.

Wrapping Up

That's all you need to know to get started with Zustand in your React application! As you can see, it's a simple and intuitive way to manage your application's state without the complexity of Redux.

Give it a try and see how it can make your state management easier, more efficient, and easier to maintain. Thanks for reading and HAPPY CODING!!!

Oldest comments (6)

Collapse
 
charlie_berg_ba7f85611050 profile image
Charlie Berg

Great intro! Quick typo in the last code example const const I thought I was seeing some ES2023 or something new 🤣

Collapse
 
jaredm profile image
professorjrod

Thanks mate ❤️

Collapse
 
joshjm profile image
Josh

in the last code block, const count = useStore(state => state); should still be accessing state.count i think

Collapse
 
jaredm profile image
professorjrod

good catch, thank you josh

Collapse
 
joshjm profile image
Josh

also, if you have multiple stores, useStore isnt going to tell the difference between them right? like if i have useCountStore and useFishStore, how do i know im getting the count, or the number of fish

Collapse
 
jaredm profile image
professorjrod

In your example you would want to use the slice pattern to implement modularity.

You can read more about that here docs.pmnd.rs/zustand/guides/slices...