Skip to content

Instantly share code, notes, and snippets.

@saintplay
Created September 21, 2023 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save saintplay/e5bf7791c6230be5b0071c942b1010a6 to your computer and use it in GitHub Desktop.
Save saintplay/e5bf7791c6230be5b0071c942b1010a6 to your computer and use it in GitHub Desktop.
useArrayState.ts
import { useState, useCallback } from 'react';
export default function useArrayState<TElement>(initialArr: Array<TElement>) {
const [arr, setArr] = useState(initialArr);
const setArrElement = useCallback((index: number, value: TElement) => {
if (!(index > -1)) return;
setArr((prevArr) => {
const arrayCopy = [...prevArr];
arrayCopy[index] = typeof value === 'function' ? value(prevArr[index]) : value;
return arrayCopy;
});
}, []);
const delArrElement = useCallback((index: number) => {
if (!(index > -1)) return;
setArr((prevArr) => {
const arrayCopy = [...prevArr];
arrayCopy.splice(index, 1);
return arrayCopy;
});
}, []);
return [arr, setArr, setArrElement, delArrElement] as const;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment