StateBeginnerFully SSR-safehooks/state/useStack.ts

useStack

LIFO stack with push/pop.

Import

TypeScript
import { useStack } from '@/hooks';

API

Signature

useStack<T>(initial?) → { stack, size, top, actions }

When to use

Use useStack instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Fully SSR-safe. Pure React state.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useStack
Editor
function History() {
  const { top, actions } = useStack<string>(['/']);
  return (
    <div>
      <p>Top: {top}</p>
      <button onClick={() => actions.push('/settings')}>Push</button>
      <button onClick={() => actions.pop()}>Pop</button>
    </div>
  );
}
Preview

Implementation source

Full library source for useStack — copy into your project when you are not installing a package yet.

hooks/state/useStack.ts
import { useCallback, useMemo, useState } from 'react';

export interface UseStackActions<T> {
  push: (item: T) => void;
  pop: () => T | undefined;
  peek: () => T | undefined;
  clear: () => void;
  reset: () => void;
}

export interface UseStackReturn<T> {
  stack: T[];
  size: number;
  top: T | undefined;
  actions: UseStackActions<T>;
}

/** LIFO stack state. */
export function useStack<T>(initialValue: T[] = []): UseStackReturn<T> {
  const [stack, setStack] = useState<T[]>(initialValue);

  const push = useCallback((item: T) => {
    setStack((prev) => [...prev, item]);
  }, []);

  const pop = useCallback(() => {
    let removed: T | undefined;
    setStack((prev) => {
      if (prev.length === 0) return prev;
      const next = [...prev];
      removed = next.pop();
      return next;
    });
    return removed;
  }, []);

  const peek = useCallback(() => stack[stack.length - 1], [stack]);
  const clear = useCallback(() => setStack([]), []);
  const reset = useCallback(() => setStack(initialValue), [initialValue]);

  return {
    stack,
    size: stack.length,
    top: stack[stack.length - 1],
    actions: useMemo(
      () => ({ push, pop, peek, clear, reset }),
      [push, pop, peek, clear, reset],
    ),
  };
}

Copy-paste example

useStack.example.tsx
'use client';

import { useStack } from '@/hooks';

export function History() {
  const { top, actions } = useStack<string>(['/']);
  return (
    <div>
      <p>Top: {top}</p>
      <button onClick={() => actions.push('/settings')}>Push</button>
      <button onClick={() => actions.pop()}>Pop</button>
    </div>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Keep state setters stable; prefer action helpers over manual setState spreads.
  • Source of truth: open hooks/state/useStack.ts for implementation details