useStack

A hook that returns a reactive Stack with push, pop, peek, and isEmpty operations.

Installation

import { useStack } from 'data-strcture-react-hooks';

Basic Usage

function MyComponent() {
  const stack = useStack(['item1', 'item2']);

  return (
    <div>
      <p>Size: {stack.size}</p>
      <button onClick={() => stack.push('item3')}>Push</button>
      <button onClick={() => stack.pop()}>Pop</button>
    </div>
  );
}

API Reference

Parameters

  • defaultValue (T[]): The initial stack values

Returns

A reactive Stack object with the following methods and properties:

Methods

  • push(item) - Adds an item to the top of the stack
  • pop() - Removes and returns the item from the top of the stack
  • peek - Returns the top item without removing it
  • isEmpty - Checks if the stack is empty

Properties

  • size - The number of items in the stack

Live Example

Try out the useStack hook with this interactive example:

Current Stack:

Top← Top

Is Empty: No

Top (Peek): Top

Stack Operations:

  • Push: Adds an item to the top of the stack
  • Pop: Removes and returns the item from the top
  • Peek: Returns the top item without removing it
  • isEmpty: Checks if the stack is empty

Examples

Basic Stack Operations

const stack = useStack(['bottom', 'middle']);

// Add items
stack.push('top');               // Stack: ['bottom', 'middle', 'top']
stack.push('new-top');           // Stack: ['bottom', 'middle', 'top', 'new-top']

// Remove items
stack.pop();                     // Returns 'new-top', Stack: ['bottom', 'middle', 'top']
stack.pop();                     // Returns 'top', Stack: ['bottom', 'middle']

// Peek at top
stack.peek;                      // Returns 'middle' (doesn't remove it)

Undo/Redo System Example

function UndoRedoSystem() {
  const undoStack = useStack([]);
  const redoStack = useStack([]);
  const [currentText, setCurrentText] = useState('');

  const saveState = (text) => {
    undoStack.push(currentText);
    setCurrentText(text);
    redoStack.clear(); // Clear redo when new action is performed
  };

  const undo = () => {
    if (!undoStack.isEmpty) {
      const previousState = undoStack.pop();
      redoStack.push(currentText);
      setCurrentText(previousState);
    }
  };

  const redo = () => {
    if (!redoStack.isEmpty) {
      const nextState = redoStack.pop();
      undoStack.push(currentText);
      setCurrentText(nextState);
    }
  };

  return (
    <div>
      <textarea
        value={currentText}
        onChange={(e) => saveState(e.target.value)}
        placeholder="Type something..."
      />

      <div>
        <button onClick={undo} disabled={undoStack.isEmpty}>
          Undo
        </button>
        <button onClick={redo} disabled={redoStack.isEmpty}>
          Redo
        </button>
      </div>

      <p>Undo stack size: {undoStack.size}</p>
      <p>Redo stack size: {redoStack.size}</p>
    </div>
  );
}

Browser History Example

function BrowserHistory() {
  const historyStack = useStack(['home']);
  const [currentPage, setCurrentPage] = useState('home');

  const navigateTo = (page) => {
    historyStack.push(currentPage);
    setCurrentPage(page);
  };

  const goBack = () => {
    if (!historyStack.isEmpty) {
      const previousPage = historyStack.pop();
      setCurrentPage(previousPage);
    }
  };

  return (
    <div>
      <h3>Current Page: {currentPage}</h3>

      <div>
        <button onClick={() => navigateTo('about')}>About</button>
        <button onClick={() => navigateTo('contact')}>Contact</button>
        <button onClick={() => navigateTo('products')}>Products</button>
      </div>

      <button onClick={goBack} disabled={historyStack.isEmpty}>
        ← Back
      </button>

      <p>History stack size: {historyStack.size}</p>
      <p>Previous page: {historyStack.peek || 'None'}</p>
    </div>
  );
}

How It Works

The useStack hook is built on top of the useArray hook and provides a stack interface with push, pop, peek, and isEmpty operations. When a mutating method (push, pop) is called, it triggers a re-render of the component by updating an internal state variable.

Stack Implementation

The Stack is implemented using an array structure for efficient operations:

  • Push: O(1) - Adds item to the top
  • Pop: O(1) - Removes item from the top
  • Peek: O(1) - Views top item without removal

TypeScript Support

The hook is fully typed and supports generic types:

const stringStack = useStack<string>(['a', 'b', 'c']);
const numberStack = useStack<number>([1, 2, 3]);
const objectStack = useStack<{id: number, name: string}>([
  { id: 1, name: 'John' }
]);