useStack
State & dataA React hook for managing LIFO stack state with immutable updates
Install
$ npm install @usefy/use-stackQuick start
import { useStack } from "@usefy/use-stack";
interface Snapshot {
id: number;
label: string;
}
function Editor() {
const [history, { push, pop, peek }] = useStack<Snapshot>([]);
const undo = () => {
const last = pop(); // remove + read the most recent change in one call
if (last) restore(last);
};
return (
<div>
<button onClick={() => push({ id: Date.now(), label: "Edit" })}>
Record change
</button>
<button onClick={undo} disabled={history.length === 0}>
Undo {peek()?.label}
</button>
<p>History depth: {history.length}</p>
</div>
);
}API reference
useStack<T>(initialState?)
Returns a tuple of the current read-only stack and a stable actions object.
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | StackInitializer<T> | empty | An array, an iterable of values, or a factory returning one (evaluated once). The last element becomes the top. |
Returns [stack, actions]
| Item | Type | Description |
|---|---|---|
stack | readonly T[] | Current stack. The last item is the top; stack[0] is the bottom |
actions | UseStackActions<T> | Stable action handlers (see below) |
Actions
| Action | Signature | Description |
|---|---|---|
push | (...items: T[]) => void | Push one or more items onto the top (the last argument ends up on top). No items is a no-op |
pop | () => T | undefined | Remove the top item and return it. Returns undefined (no-op) when empty |
peek | () => T | undefined | Read the top item without mutating (stable, always reflects latest state) |
clear | () => void | Remove all items. Clearing an empty stack is a no-op |
reset | () => void | Restore the initial values (a fresh copy) |
Reading top / bottom / size
The returned stack is a read-only array, so these derive directly from it — no extra state needed:
const [stack] = useStack<number>([1, 2, 3]);
const top = stack[stack.length - 1]; // 3 (next to pop)
const bottom = stack[0]; // 1 (oldest item)
const size = stack.length; // 3
The returned
stackis areadonly T[], so callingstack.push(...)directly is a TypeScript error. Use the actions — mutating the array in place would bypass React state and break re-renders.
Go deeper
This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.