Home Arrow Icon Knowledge base Arrow Icon Global Arrow Icon Can you show an example of using Zustand with React hooks


Can you show an example of using Zustand with React hooks


Here is an example of using Zustand with React hooks to manage state:

javascript
import React from 'react';
import { create } from 'zustand';

// Create the store
const useStore = create((set) => ({
  todos: [],
  addTodo: (title) => set((state) => ({ todos: [...state.todos, { title }] })),
  removeTodo: (index) => set((state) => ({ todos: state.todos.filter((_, i) => i !== index) })),
}));

// Usage in a component
function TodoList() {
  const todos = useStore((state) => state.todos);
  const addTodo = useStore((state) => state.addTodo);
  const removeTodo = useStore((state) => state.removeTodo);

  return (
    <div>
      <h2>Todo List</h2>
      <ul>
        {todos.map((todo, index) => (
          <li key={index}>
            {todo}
            <button onClick={() => removeTodo(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <input
        type="text"
        placeholder="Add a new todo"
        onChange={(e) => addTodo(e.target.value)}
      />
    </div>
  );
}

export default TodoList;

In this example, we create a store using Zustand's `create` function. The store has two actions: `addTodo` and `removeTodo`. These actions update the `todos` state array.

In the `TodoList` component, we use the `useStore` hook to access the `todos` state and the `addTodo` and `removeTodo` actions. We then render the list of todos and provide a form to add new todos.

Explanation

1. Store Creation: The `create` function from Zustand is used to create a store. The store is initialized with an empty array of todos and two actions: `addTodo` and `removeTodo`.

2. Actions: The `addTodo` action adds a new todo to the list by spreading the existing list and adding a new item. The `removeTodo` action removes a todo from the list by filtering out the item at the specified index.

3. Component Usage: In the `TodoList` component, we use the `useStore` hook to access the `todos` state and the `addTodo` and `removeTodo` actions.

4. Rendering: The component renders the list of todos and provides a form to add new todos. When the form is submitted, the `addTodo` action is called with the new todo title. When a todo is removed, the `removeTodo` action is called with the index of the todo to be removed.

This example demonstrates how Zustand can be used to manage state in a React application using hooks. It provides a simple and efficient way to manage state and actions in your application[1][2][4].

Citations:
[1] https://www.ankurkedia.com/blog/state-management-zustand
[2] https://tkdodo.eu/blog/zustand-and-react-context
[3] https://stackoverflow.com/questions/76908725/i-need-to-call-a-hook-inside-a-zustand-action
[4] https://www.bigbinary.com/blog/upgrading-react-state-management-with-zustand
[5] https://tkdodo.eu/blog/working-with-zustand