BFE.devでのAI解答例 - React コーディング問題
12. useArray()
import { useState } from 'react';function useArray(initialArray) { const [value, setValue] = useState(initialArray); const push = (item) => { setValue((prev) => [...prev, item]); }; const removeByIndex = (index) => { setValue((prev) => { prev.splice(index, 1); return [...prev]; }); }; return { value, push, removeByIndex, };}export default useArray;
Explanation:
We can define a custom hook useArray
which takes an initialArray
and returns an object containing value
, push
and removeByIndex
methods.
value
- stores the current state of the array.push
- adds a new item to the end of the array.removeByIndex
- removes the item at the specified index from the array.
useState
hook is used to create a value
state that holds the initial array provided.
push
uses the setValue
function returned from useState
to update the value
state with the new array that is created by destructuring the previous state and appending the new item.
removeByIndex
uses the setValue
function to update the value
state by creating a new array that removes the item at the specified index. We do this by using the splice
method to remove the item from the previous state, and returning a new array using the spread operator.
Finally, we return an object with value
, push
, and removeByIndex
methods.