Skip to content
usefy

useStack

State & data

A React hook for managing LIFO stack state with immutable updates

Install

$ npm install @usefy/use-stack

Quick start

useStack.tsx
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

ParameterTypeDefaultDescription
initialStateStackInitializer<T>emptyAn array, an iterable of values, or a factory returning one (evaluated once). The last element becomes the top.

Returns [stack, actions]

ItemTypeDescription
stackreadonly T[]Current stack. The last item is the top; stack[0] is the bottom
actionsUseStackActions<T>Stable action handlers (see below)

Actions

ActionSignatureDescription
push(...items: T[]) => voidPush one or more items onto the top (the last argument ends up on top). No items is a no-op
pop() => T | undefinedRemove the top item and return it. Returns undefined (no-op) when empty
peek() => T | undefinedRead the top item without mutating (stable, always reflects latest state)
clear() => voidRemove all items. Clearing an empty stack is a no-op
reset() => voidRestore 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 stack is a readonly T[], so calling stack.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.

More in state & data