DEV Community

Cover image for Zustand, simplified redux
Nelson chege
Nelson chege

Posted on • Updated on

Zustand, simplified redux

Having Used Redux toolkit, it really does the job well having no issues with it. Setting Up the store makes using it in the rest of your project quite Easy.

But one thing about creating the Redux stores is that it's really verbose and you have to write a lot more boilerplate code.

This is the part where Zustand comes in, Doing what redux is doing but with really less code. ill be creating a simple project to show you how easy it is to use Zustand

first, create a folder in the root directory that will contain the costume Hook for our state

touch store/useItemsStore.js

in that file, the hook is created as follows

import {create} from 'zustand';

const useMyStore = create((set) => ({
  items: [], // initial state
  addItem: (newItem) => set((state) => ({ items: [...state.items, newItem] })),
  deleteItem: (index) =>
    set((state) => ({ items: state.items.filter((_, i) => i !== index) })),
}));
Enter fullscreen mode Exit fullscreen mode

this will create an empty list and two functions for adding and deleting items

when you want to use the above state and functions in you components you'll do the following

import { useMyStore } from './store/useItemsStore';

function MyComponent() {
  const addItem = useMyStore((state) => state.addItem);

  const handleClick = () => {
    addItem('New Item');
  };

  return (
    <>
      <button onClick={handleClick}>Add Item</button>
      {/* Render the list of items here */}
     <ul>
        {items.map((item, index) => (
          <li key={index}>
            {item} <button onClick={() => handleDelete(index)}>Delete</button>
          </li>
        ))}
      </ul>
    </>
  );
}
Enter fullscreen mode Exit fullscreen mode

And that's it. not a lot of code and still functions similarly to redux. it has been fun using it for small side projects so far

here is a simple Todo App that i use Zustand to manage my state: https://react-zustand.netlify.app/

Top comments (0)