The task is to create a useArray hook where you can push items into and remove items from the array.
The boilerplate code:
// This is a React problem from BFE.dev
import React, { useState } from 'react'
type UseArrayActions<T> = {
push: (item: T) => void,
removeByIndex: (index: number) => void
}
export function useArray<T>(initialValue: T[]): { value: T[] } & UseArrayActions<T> {
const state = useState()
}
// if you want to try your code on the right panel
// remember to export App() component like below
// export function App() {
// const { value } = useArray([1, 2, 3])
// return <div>
// {value}
// </div>
// }
The first step is to create the state variable
const [value, setValue] = useState<T[]>(initialValue)
Next, the function to push items into the array is created
const push = useCallback((item: T) => {
setValue(prev => [...prev, item])
}, [])
To add items to an array, the current values(...prev) in the array are passed to the state setter alongside the item to be added. We used a useCallback hook to keep the function the same across multiple renders, if the function itself isn't changed.
The function to remove items from the array is then created
const removeByIndex = useCallback((index: number) => {
setValue(prev => prev.filter((_, i) => i !== index))
}, [])
To remove items from the array, you filter the items based on their index.
The final code looks like this
// This is a React problem from BFE.dev
import React, { useState } from 'react'
type UseArrayActions<T> = {
push: (item: T) => void,
removeByIndex: (index: number) => void
}
export function useArray<T>(initialValue: T[]): { value: T[] } & UseArrayActions<T> {
const [value,setValue] = useState<T[]>(initialValue)
const push = useCallback((item: T) => {
setValue(prev => [...prev, item])
}, [])
const removeByIndex = useCallback((index: number) => {
setValue(prev => prev.filter((_, i) => i !== index))
}, [])
return { value, push, removeByIndex}
}
// if you want to try your code on the right panel
// remember to export App() component like below
// export function App() {
// const { value } = useArray([1, 2, 3])
// return <div>
// {value}
// </div>
// }
That's all folks!
Top comments (0)