Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save techcoder2007/512db0127e039c90d8983cc6757d4ab6 to your computer and use it in GitHub Desktop.
Save techcoder2007/512db0127e039c90d8983cc6757d4ab6 to your computer and use it in GitHub Desktop.
React State Management — using Zustand
Zustand is a lightweight state management library for React that allows you to manage global state with minimal setup. Here's a basic overview of how to use Zustand for state management in a React application:
Installation: First, you need to install Zustand in your project. You can do this using npm or yarn:
npm install zustand
# or
yarn add zustand
Create a Store: Zustand uses the concept of a store to manage your application state. You create a store using the create function provided by Zustand. Inside this store, you define your state and any actions to modify that state. For example:
import create from 'zustand';
const useStore = create((set) => ({
count: 0,
increment: () => set((state) => ({ count: state.count + 1 })),
decrement: () => set((state) => ({ count: state.count - 1 })),
}));
export default useStore;
Use the Store in Components: Once you've defined your store, you can use it in your React components using the useStore hook:
import React from 'react';
import useStore from './useStore';
const Counter = () => {
const { count, increment, decrement } = useStore();
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
</div>
);
};
export default Counter;
Accessing State and Actions: In your component, you can access the state and actions returned by the useStore hook. Whenever the state is updated using one of the actions, all components using that state will re-render with the updated values.
const { count, increment, decrement } = useStore();
Cleanup: Zustand automatically cleans up its subscriptions when components unmount, so you don't need to worry about memory leaks.
That's a basic overview of how to use Zustand for state management in a React application. It's simple and easy to use, making it a great choice for smaller projects or when you want a lightweight solution for managing global state.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment