A simple React hook for managing global state with zero boilerplate.
A lightweight React hook that provides global state management without providers, context, or complex setup.
- 🧠 Simple API - Just like
useStatebut globally shared - �� No Providers - No Context. No extra setup required
- ⚡ Global by default - All state is automatically shared across components
- 🧩 Works with any state shape: primitives, arrays, objects
- 🧼 Built with React's
useSyncExternalStorefor optimal performance
const [count, setCount] = useGlobalState("counter", 0);const [user, setUser] = useGlobalState("user", { name: "John", age: 25 });// ComponentA.tsx
export function ComponentA() {
const [count, setCount] = useGlobalState("shared-count", 0);
return (
<div>
<h3>Component A</h3>
<p>Count: {count}</p>
<button onClick={() => setCount(count + 1)}>Increment</button>
</div>
);
}
// ComponentB.tsx
export function ComponentB() {
const [count] = useGlobalState("shared-count", 0); // same key
return (
<div>
<h3>Component B</h3>
<p>Count from A: {count}</p>
</div>
);
}const [state, setState] = useGlobalState(key, initialValue);key: Unique string identifier for the state entryinitialValue: Initial value (only used if the key doesn't exist yet)- Returns:
[state, setState]tuple just likeuseState
const [count, setCount] = useGlobalState("counter", 0);
// Direct assignment
setCount(5);
// Increment
setCount(count + 1);const [user, setUser] = useGlobalState("user", {
name: "Alex",
age: 25
});
// Update entire object
setUser({ name: "John", age: 30 });
// Note: This replaces the entire object, not mergeconst [todos, setTodos] = useGlobalState("todos", []);
// Add todo
setTodos([...todos, { id: 1, text: "Learn React", done: false }]);
// Toggle todo
setTodos(todos.map(todo =>
todo.id === 1 ? { ...todo, done: !todo.done } : todo
));- Components using the same
keywill share the same state - The
initialValueis only used when the key doesn't exist yet - Subsequent calls with the same key will get the existing value
- Unlike some state management libraries, this hook does direct assignment
- When updating objects, you need to manually merge properties:
// ❌ This will replace the entire object
setUser({ name: "John" }); // loses age property
// ✅ This preserves other properties
setUser({ ...user, name: "John" });- Global Store: Uses a Map to store all state entries
- Subscription System: Components subscribe to state changes via listeners
- Automatic Re-renders: When state changes, all subscribed components re-render
- No Providers: Uses React's
useSyncExternalStorefor external state management
MIT