Skip to content

Instantly share code, notes, and snippets.

@lalalam123
Last active September 1, 2023 18:03
Show Gist options
  • Save lalalam123/2276d793ebf06bce019959413f8e82bf to your computer and use it in GitHub Desktop.
Save lalalam123/2276d793ebf06bce019959413f8e82bf to your computer and use it in GitHub Desktop.
Custom Hooks for arrays
import { useState } from 'react';
type ArrayStateActions<T> = {
add: (item: T) => void;
remove: (item: T) => void;
clear: () => void;
};
const useArrayState = <T>(
inistialItems: T[],
): [T[], ArrayStateActions<T>] => {
const [items, setItems] = useState(initialItems);
const add = (item: T) => setItems([...items, item]);
const remove = (item: T) => setItems([...items.filter((i)=> i !== item)]);
const clear = () => setItems([]);
return [items, {add, remove, clear}];
};
export default useArrayState;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment