API Reference
useStack

useStack

This hook manages a Stack abstract data type. A stack is a Last-In-First-Out (LIFO) data model where elements are added to and removed from the top only. You can learn more about how stacks work on Wikipedia (opens in a new tab) or the NIST (opens in a new tab).

Installation

To use this custom hook in your React project, you can follow these steps:

  1. Make sure you have @ridgehkr/useful installed in your application. If not, you can get started by following the installation instructions.

  2. Import useStack into your component.

import { useStack } from '@ridgehkr/useful'

Example

Stack.tsx
import { useState } from 'react'
import { useStack, Stack } from '@ridgehkr/useful'
 
function StackExample() {
  // Initialize the stack using the useStack custom hook
  const stack: Stack<number> = useStack<number>()
 
  // State to store user input for pushing onto the stack
  const [inputValue, setInputValue] = useState<number | string>('')
  // State to display the result of stack operations
  const [result, setResult] = useState<string | undefined>('')
 
  // Function to handle pushing a value onto the stack
  const handlePush = () => {
    if (typeof inputValue === 'number' && !isNaN(inputValue)) {
      stack.push(inputValue)
      setInputValue('')
      setResult(`Pushed ${inputValue} onto the stack.`)
    } else {
      setResult('Please enter a valid number.')
    }
  }
 
  // Function to handle popping a value from the stack
  const handlePop = () => {
    const poppedItem = stack.pop()
    if (poppedItem !== undefined) {
      setResult(`Popped ${poppedItem} from the stack.`)
    } else {
      setResult('The stack is empty.')
    }
  }
 
  // Function to handle peeking at the top of the stack
  const handlePeek = () => {
    const topItem = stack.peek()
    if (topItem !== undefined) {
      setResult(`Top of the stack: ${topItem}`)
    } else {
      setResult('The stack is empty.')
    }
  }
 
  // Function to handle clearing the stack
  const handleClear = () => {
    stack.clear()
    setResult('Stack cleared.')
  }
 
  // Render the stack demo component
  return (
    <div>
      <h1>Stack Demo</h1>
      <div>
        <input
          type='number'
          placeholder='Enter a number'
          value={inputValue}
          onChange={(e) => setInputValue(Number(e.target.value))}
        />
        <button onClick={handlePush}>Push</button>
        <button onClick={handlePop}>Pop</button>
        <button onClick={handlePeek}>Peek</button>
        <button onClick={handleClear}>Clear</button>
      </div>
      <div>
        <p>Stack: {stack.toArray().join(', ')}</p>
        <p>{result}</p>
        <p>Stack Size: {stack.size}</p>
      </div>
    </div>
  )
}

API Reference

Hook Signature

useStack<T>(initialItems?: T[]): Stack<T>

Parameters

initialItems accepts an optional array of initial values.

PropertyTypeRequiredDescription
initialItemsT[]noSets the initial items for the Stack

Return Value

useStack returns a Stack object with the following methods and values:

PropertyTypeReturnsDescription
items() => {}An array containing the items in the stackReturns the items in the stack
sizenumberThe number of items in the stackReturns the number of items in the stack
push(item: T): void => {}voidPushes an item onto the top of the stack
pop(): T | undefined => {}The popped item or undefined if the stack is emptyRemoves and returns the top item from the stack
peek(): T => {}The top item or undefined if the stack is emptyReturns the top item from the stack (but does not remove it)
clear(): void => {}voidRemoves all items from the stack
contains(item: T): boolean => {}booleanWhether or not the Stack contains item T
toArray(): T[] => {}T[]Returns an array representation of the Stack