Created
December 13, 2023 11:13
-
-
Save aaroniker/995a133b89def16dda943641f1ae1b07 to your computer and use it in GitHub Desktop.
useArrayState React Hook w/ Typescript Support
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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