Developing Simple Crud Operation with Zustand NextJs: Zustand for State Management


zustand nextjs

As per Zustand Docs, It is cute with claws state management library that reduces the complexity of global state management in React apps without requiring the overhead of conventional libraries like Redux or React query.

I'm assuming you're no stranger to how state management works in React Next.js apps, but on behalf of the introduction, I am explaining it one more time.

In software development, state management involves managing and updating the data that decides how an application behaves and looks. 

Consider an e-commerce website's shopping cart function, for example. The products in the cart, their amounts, and the total cost would all be listed by the state. The application modifies the state of the cart when a user adds an item, recalculating totals and perhaps updating associated components like the status of the checkout button or mini cart. 

This is where state management libraries, like Zustand or Redux, come in, and make this process easier by offering standardized methods for stating, updating, and synchronizing data between components.

Zustand with NextJs - Simple Crud Operation with examples

I am skipping the installation part, as this is very basic. So let's jump to defining the Zustand global store and define actions.

Create Zustand Store & Define your CRUD Actions

Define Zustand dynamic store. I will here use a nested array as an example for Zustand global state management. 

This is the array, I will be using.

 
  const initialState = {
    items: [
      {
        id: 1,
        name: "Item 1",
        children: [
          {
            id: 11,
            name: "Child 1-1",
            grandchildren: [
              { id: 111, name: "Grandchild 1-1-1" },
              { id: 112, name: "Grandchild 1-1-2" },
            ],
          },
        ],
      },
      {
        id: 2,
        name: "Item 2",
        children: [],
      },
    ],
  };


Now create your global store, and define your action as you do with Redux.

 
  import create from "zustand";

  const useStore = create((set) => ({
    data: initialState.data,

    // Adding to my new item
    addItem: (item) =>
      set((state) => ({
        data: [...state.data, item],
      })),

    // Updating my item
    updateItem: (id, newItem) =>
      set((state) => ({
        data: state.data.map((item) =>
          item.id === id ? { ...item, ...newItem } : item
        ),
      })),

    // Removing my item
    removeItem: (id) =>
      set((state) => ({
        data: state.data.filter((item) => item.id !== id),
      })),

  }));

  export default useStore;


Now create functions for adding, updating, and removing items from the array. You need to use the global state you declare with Zustand and render the data as you want.

 
  import useStore from "../path/to/store";

  function MyComponent() {
    const data = useStore((state) => state.data);
    const addItem = useStore((state) => state.addItem);
    const removeItem = useStore((state) => state.removeItem);
const updateItem = useStore((state) => state.updateItem);

   
    const handleAddItem = () => {
      addItem({ id: 3, name: "Item 3", children: [] });
    };

    const handleRemoveItem = (id) => {
      removeItem(id);
    };

const handleUpdateItem = (id, newItem) => {
updateItem(id, newItem); };


    return (
      <div>
        {/* Render your data as you want */}
      </div>
    );
  }

  export default MyComponent;


Zustand provides a straightforward, hook-based API for managing state within components. It is a lightweight state management library for React. Compared to other alternatives like Redux, it excels at eliminating boilerplate code, which makes it simple to integrate and maintain. Zustand makes use of Immer to provide immutable updates, guarantee effective state management, and boost developer output. Because of its adaptability, a state can be handled across components without sacrificing speed.


Frequently Asked Questions (FAQs)

Where to use Zustand?

Imagine you're developing a shopping cart feature for an e-commerce site using React or NextJs. You need to keep track of items in the cart across different pages and allow users to add or remove items.

Instead of passing data through multiple layers of components or using a complex Redux setup, you can use Zustand.

Why use Zustand?

I don't want to bore you with things like "Why Zustand over Redux" or "Why Zustand over Context"!! I mean you should use them. They are very much needed for our Major applications. 

Zustand is favored above other state management tools like Redux because of its simplicity and minimalism. 

By using the Context API and React hooks, it provides a lightweight approach without compromising on strong state management features. 

When to use Zustand?

Zustand is therefore perfect for small- to medium-sized applications where performance and simplicity are more important than large feature sets and intricate configuration.

Where does Zustand Store Data?

Zustand uses React's Context API to store data inside the React component tree. 

Zustand specifically builds an internal context provider component that stores the state and makes it available to any component that uses the `useStore` hook or `useSelector` method to subscribe to it. Zustand's state will always be accessible to components that require it.

Is Zustand Synchronous or Asynchronous?

Zustand can proudly be used with asynchronous processes as required. In Zustand's state update functions, you can use asynchronous actions to carry out asynchronous operations (receiving data from an API).

How to use Zustand to add your data to an Array?


 
  const useStore = create((set) => ({
    items: [],

   
    addItem: (item) => set((state) => ({
      items: [...state.items, item]
    })),
  }));

function ItemList() {
const { items, addItem } = useStore(); const handleAddItem = () => { const newItem = { id: items.length + 1, name: `Item ${items.length + 1}` }; addItem(newItem); };



How to use Zustand to add your data to a Local Storage?




  const loadStateFromLocalStorage = () => {
    try {
      const serializedState = localStorage.getItem(LOCAL_STORAGE_KEY);
      return serializedState ? JSON.parse(serializedState) : {};
    } catch (error) {
      console.error('Error loading state from Local Storage:', error);
      return {};
    }
  };

  const useStore = create((set) => ({
    items: loadStateFromLocalStorage().items || [],

    addItem: (item) => set((state) => {
      const updatedItems = [...state.items, item];
      localStorage.setItem(LOCAL_STORAGE_KEY, JSON.stringify({ items: updatedItems }));
      return { items: updatedItems };
    }),
  }));



codegirl

Hello, I’m Sangita, person behind "codegirl", a dedicated web developer. Crafting digital experiences is not just my job; it’s my passion. Let’s build something exceptional together!

Post a Comment

Previous Post Next Post