Skip to content

Instantly share code, notes, and snippets.

@aaroniker
Created December 13, 2023 11:13
Show Gist options
  • Select an option

  • Save aaroniker/995a133b89def16dda943641f1ae1b07 to your computer and use it in GitHub Desktop.

Select an option

Save aaroniker/995a133b89def16dda943641f1ae1b07 to your computer and use it in GitHub Desktop.
useArrayState React Hook w/ Typescript Support
const useArrayState = <T>(initialState: T[] = []) => {
const [state, setState] = useState<T[]>(initialState);
const add = (newValue: T) => {
setState((currentState) => [...currentState, newValue]);
};
const remove = (index: number) => {
setState((currentState) => {
const newState = [...currentState];
newState.splice(index, 1);
return newState;
});
};
return [state, { add, remove }] as const;
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment