Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 | 25x 25x 55x 55x 25x 55x 55x 55x 55x 12x 55x 16x 16x 16x 55x 4x 55x 2x 55x 3x 55x 25x 55x | import { useCallback, useMemo, useRef, useState } from "react";
import type {
StackInitializer,
UseStackActions,
UseStackReturn,
} from "./types";
/**
* Resolve a {@link StackInitializer} to a concrete array. A function
* initializer is invoked once; any iterable is copied into a fresh array so the
* caller's original object is never mutated.
*/
function resolveInitial<T>(initial?: StackInitializer<T>): T[] {
const value = typeof initial === "function" ? initial() : initial;
return value ? [...value] : [];
}
/**
* A React hook for managing a LIFO (last-in, first-out) stack as React state
* with immutable, ergonomic updates.
*
* The LIFO sibling of {@link https://npmjs.com/package/@usefy/use-queue | useQueue}
* — identical in shape and conventions, but pushes and pops from the same end.
*
* Returns a tuple of the current (read-only) stack and a stable set of actions.
* The **top** of the stack is the last element (`stack[stack.length - 1]`, the
* next item to be popped) and new items are pushed onto the end. Every mutation
* produces a brand-new array so React re-renders correctly and the previous
* state is never mutated in place. Updates that would not change anything
* (pushing nothing, popping from or clearing an empty stack) are skipped to
* avoid needless re-renders.
*
* Features:
* - Immutable updates (new array on every change) with a `readonly T[]` return type
* - LIFO semantics: `push` and `pop` both operate on the top (the array's end)
* - `pop` returns the popped item (or `undefined` when empty)
* - `peek` reads the top item without mutating; stable and always current
* - Stable action identities — safe to use as effect dependencies
* - `useState`-style lazy initialization; accepts an array, iterable, or factory
* - Full TypeScript generics for the element type
*
* Reading `top` / `bottom` / `size` is done directly on the returned stack:
* `stack[stack.length - 1]`, `stack[0]`, and `stack.length` respectively.
*
* @template T - Element type.
* @param initialState - Initial items, or a factory returning them. Defaults to empty.
* @returns `[stack, { push, pop, peek, clear, reset }]`
*
* @example
* ```tsx
* // An undo / navigation history 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() ? ` (${peek()!.label})` : ""}
* </button>
* <p>History depth: {history.length}</p>
* </div>
* );
* }
* ```
*
* @example
* ```tsx
* // Push, pop from the top (LIFO), reset
* const [s, { push, pop, reset }] = useStack<number>([1, 2]);
* push(3, 4); // stack: [1, 2, 3, 4] (4 is the top)
* pop(); // returns 4, stack: [1, 2, 3]
* reset(); // back to [1, 2]
* ```
*/
export function useStack<T>(
initialState?: StackInitializer<T>
): UseStackReturn<T> {
// Resolve the initial stack exactly once and keep it for `reset`.
const initialRef = useRef<T[] | null>(null);
if (initialRef.current === null) {
initialRef.current = resolveInitial(initialState);
}
const [stack, setStack] = useState<T[]>(() => [
...(initialRef.current as T[]),
]);
// Mirror the latest stack so `pop`/`peek` can be stable callbacks that still
// read fresh state.
const stackStateRef = useRef(stack);
stackStateRef.current = stack;
const push = useCallback((...items: T[]) => {
setStack((prev) => (items.length === 0 ? prev : [...prev, ...items]));
}, []);
const pop = useCallback((): T | undefined => {
// Capture the top from the mirrored state so we can return it.
const top = stackStateRef.current[stackStateRef.current.length - 1];
setStack((prev) => (prev.length === 0 ? prev : prev.slice(0, -1)));
return top;
}, []);
const peek = useCallback(
(): T | undefined =>
stackStateRef.current[stackStateRef.current.length - 1],
[]
);
const clear = useCallback(() => {
setStack((prev) => (prev.length === 0 ? prev : []));
}, []);
const reset = useCallback(() => {
setStack([...(initialRef.current as T[])]);
}, []);
const actions = useMemo<UseStackActions<T>>(
() => ({ push, pop, peek, clear, reset }),
[push, pop, peek, clear, reset]
);
return [stack, actions];
}
|