Created
September 21, 2023 01:10
-
-
Save saintplay/e5bf7791c6230be5b0071c942b1010a6 to your computer and use it in GitHub Desktop.
useArrayState.ts
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
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