Skip to content

useArray() ​

useArray<T>(initialArray?): object

Defined in: hooks/state/useArray.ts:45

A custom React hook for managing an array state with helper functions to modify it.

Type Parameters ​

T ​

T

The type of elements in the array.

Parameters ​

initialArray? ​

T[] = []

The initial array state (defaults to an empty array).

Returns ​

object

An object containing:

  • array: The current state of the array.
  • set: Function to replace the entire array.
  • push: Function to add an item to the end of the array.
  • remove: Function to remove an item at a specific index.
  • clear: Function to clear the array.

array ​

array: T[]

set ​

set: Dispatch<SetStateAction<T[]>>

push() ​

push: (item) => void

Parameters ​

item ​

T

Returns ​

void

remove() ​

remove: (index) => void

Parameters ​

index ​

number

Returns ​

void

clear() ​

clear: () => void

Returns ​

void

Example ​

tsx
import { useArray } from '@zl-asica/react';

const MyComponent = () => {
  const { array, push, remove, clear } = useArray<number>([1, 2, 3]);

  return (
    <div>
      <ul>
        {array.map((item, index) => (
          <li key={index}>
            {item}{' '}
            <button onClick={() => remove(index)}>Remove</button>
          </li>
        ))}
      </ul>
      <button onClick={() => push(array.length + 1)}>Add</button>
      <button onClick={clear}>Clear</button>
    </div>
  );
};

Released under the MIT License.