Skip to content

useStack

Manage a stack of items

The useStack hook is helpful when you want to manage a stack of items (based on stack data structure).

It provides with helper methods like push, pop, peek, clear, set, reset and additional properties likesize.

useStack

Last Item
Item 1
Size: 1Try adding and removing items on the stack.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useStack } from '@abhushanaj/react-hooks';
function App() {
const [stack, stackControls] = useStack([]);
const { clear, push, pop, size, reset, peek } = stackControls;
return (
<div>
<p>Size: {size}</p>
<button onClick={clear}>Clear</button>
<button onClick={() => push(stack.length)}>Add Item</button>
<button
onClick={() => {
const poppedItem = pop();
console.log(poppedItem);
}}
>
Remove Item
</button>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
initialStackArray<T> (optional)The initial stack with items prefilled.[]

Return Value

ParameterTypeDescriptionDefault
stackArray<T>The current stack.N/A
stackControlsStackControlsThe control options for the stack to add, remove etc.N/A

Types Reference

1. StackControls

ParameterTypeDescriptionDefault
sizenumberReturns the size of the stack.N/A
clear()=>voidClears the stack to an empty state.N/A
reset()=>voidResets the stack back to the inital state.N/A
set(newStack: Array<T>)=>voidReplaces current stack with newStack.N/A
push(newItem: T)=>voidAdds a new item to the stack. Item is added at the end of the stack.N/A
pop()=>T|undefinedRemoves the last entry from the stack and returns it.N/A
peek()=>T|undefinedReturns the last entry from the stack, but does not alter stack state.N/A