Skip to content

useArray

Hook to use Array data structure to handle component state with all Array methods.

Demo

INFO

The component has:

  • A useArray internal state.
  • An uncontrolled input with inputRef ref used to execute buttons actions.
  • A button Push that push the input value into state by push method of Array interface.
  • A button Pop that remove last item into state by pop method of Array interface.
Loading demo…
Show source code
tsx
import { useCallback, useRef } from "react";
import { useArray } from "../../../..";

const UseArray = () => {
	const array = useArray<string>();

	const inputRef = useRef<HTMLInputElement>(null);

	const pop = useCallback(() => {
		array.pop();
	}, [array]);

	const push = useCallback(() => {
		array.push(inputRef.current!.value);
	}, [array]);

	return (<>
		{array.join(",")}
		<br />
		<input ref={inputRef} type="text" />
		<br />
		<div style={{ marginTop: 15, gridTemplateColumns: 'auto auto', justifyContent: 'center', display: 'grid', gap: '5px' }}>
			<button onClick={push}>Push</button>
			<button onClick={pop}>Pop</button>
		</div>
	</>);
}

UseArray.displayName = "UseArray";

export { UseArray }

Types

UseArrayProps

  • @template T - The type of the elements contained in the array.

Parameters accepted by useArray.

PropertyTypeRequiredDescription
initialStateArray<T> \| (() => Array<T>)The initial array state. Accepts either a direct array value or a lazy initializer function invoked only on the first render, avoiding unnecessary re-creation of the initial value on subsequent renders. When omitted, the array is initialised as empty.

UseArrayResult

  • @template T - The type of the elements contained in the array.

Return value of useArray. A reactive Array<T> whose mutating methods automatically synchronise the underlying React state. All standard read-only methods (map, filter, find, reduce, etc.) are inherited unchanged from Array<T>. The following mutating methods are overridden to trigger a re-render:

MethodBehaviour
copyWithinCopies a sequence of elements within the array and updates state.
fillFills a range of indices with a static value and updates state.
popRemoves and returns the last element, updating state.
pushAppends one or more elements and returns the new length, updating state.
reverseReverses the array in place and updates state.
shiftRemoves and returns the first element, updating state.
sortSorts the array (optionally with a comparator) and updates state.
spliceAdds/removes elements at a given index and returns removed items.
unshiftPrepends one or more elements and returns the new length, updating state.
ts
export type UseArrayResult<T> = Array<T> & {
	/** Copies a sequence of elements within the array and triggers a re-render. */
	copyWithin(target: number, start: number, end?: number): T[];

	/** Fills a range of indices with `value` and triggers a re-render. */
	fill(value: T, start?: number, end?: number): T[];

	/** Removes and returns the last element, triggering a re-render. */
	pop(): T | undefined;

	/**
	 * Appends one or more elements to the end of the array, triggering a re-render.
	 * Returns the new array length.
	 */
	push(...items: T[]): number;

	/** Reverses the array in place and triggers a re-render. */
	reverse(): T[];

	/** Removes and returns the first element, triggering a re-render. */
	shift(): T | undefined;

	/**
	 * Sorts the array in place, optionally using `compareFn`, and triggers a
	 * re-render.
	 */
	sort(compareFn?: (a: T, b: T) => number): T[];

	/**
	 * Adds and/or removes elements starting at `start`. Returns the array of
	 * removed elements and triggers a re-render.
	 */
	splice(start: number, deleteCount: number, ...items: T[]): T[];

	/**
	 * Prepends one or more elements to the beginning of the array, triggering a
	 * re-render. Returns the new array length.
	 */
	unshift(...items: T[]): number;
};

Released under the MIT License.