Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active February 28, 2026 08:08
Show Gist options
  • Select an option

  • Save Kcko/31a32b57d035963e95d9298b7fd2706b to your computer and use it in GitHub Desktop.

Select an option

Save Kcko/31a32b57d035963e95d9298b7fd2706b to your computer and use it in GitHub Desktop.
// 1 install
npm install zustand
// 2 create
// store.js
import { create } from 'zustand';
const useStore = create((set) => ({
count: 0, // Initial state
increase: () => set((state) => ({ count: state.count + 1 })),
decrease: () => set((state) => ({ count: state.count - 1 })),
}));
export default useStore;
// 3 use
// App.js
import React from 'react';
import useStore from './store';
const Counter = () => {
const { count, increase, decrease } = useStore((state) => ({
count: state.count,
increase: state.increase,
decrease: state.decrease,
}));
return (
<div>
<h1>Count: {count}</h1>
<button onClick={increase}>Increase</button>
<button onClick={decrease}>Decrease</button>
</div>
);
};
export default Counter;
//4 optional - middleware
import { create } from 'zustand';
import { persist } from 'zustand/middleware';
const useStore = create(
persist(
(set) => ({
count: 0,
increase: () => set((state) => ({ count: state.count + 1 })),
}),
{ name: 'counter-storage' } // Key for localStorage
)
);
export default useStore;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment