Introduction
Zustand is a small library for state management in React applications. It provides a simple and efficient way to manage global state without the boilerplate of more complex libraries.
Using Zustand, we can create a custom store to manage the selected package manager across different components in our application. This allows users to select their preferred package manager (e.g., npm, yarn, pnpm) and have the command snippets update accordingly.
Installation
shadcn/ui
shadcn/ui Command
pnpm dlx shadcn@latest add https://code-blocks.pheralb.dev/r/package-manager-store.jsonManual
- Install Zustand:
Zustand
pnpm i zustand- Create a custom store
stores/packageManager.ts:
.ts
import { create } from "zustand";
import { persist } from "zustand/middleware";
type PackageManager = "npm" | "pnpm" | "yarn" | "bun";
interface PackageManagerState {
packageManager: PackageManager;
setPackageManager: (packageManager: PackageManager) => void;
}
const usePackageManager = create<PackageManagerState>()(
persist(
(set) => ({
packageManager: "pnpm",
setPackageManager: (packageManager: PackageManager) =>
set(() => ({ packageManager })),
}),
{
name: "package-manager-store",
},
),
);
export { type PackageManager, usePackageManager };Usage
Import the store and use it in your components:
.tsx
import { usePackageManager } from "@/stores/packageManager";
const PackageManagerSelector = () => {
const { packageManager, setPackageManager } = usePackageManager();
return (
<select
value={packageManager}
onChange={(e) => setPackageManager(e.target.value)}
>
<option value="npm">npm</option>
<option value="yarn">yarn</option>
<option value="pnpm">pnpm</option>
</select>
);
};