The useArray Hook is used to easily deal with arrays, without having to use the rest/spread syntax.
The Array Hook returns an object with the following:
- value: The current array
- setValue: Sets a new array as the value
- add: Adds a given element to the array
- clear: Removes all elements from the array
- removeIndex: Removes an element from the array by its index
- removeById: Removes an element from the array by its id (assuming that the elements in the array are objects with an id key)
It works as follows:
- First, we import the useArray Hook from react-hookedup:
import React from 'react'
import { useArray } from 'react-hookedup'
- Then, we define the component and the Array Hook, with the default value of ['one', 'two', 'three']:
export default function UseArray () {
const { value, add, clear, removeIndex } = useArray(['one', 'two', 'three'])
- Now, we display the current array as JSON:
return (
<div>
<p>current array: {JSON.stringify(value)}</p>
- Then, we display a button to add an element:
<button onClick={() => add('test')}>add element</button>
- Next, we display a button to remove the first element by index:
<button onClick={() => removeIndex(0)}>remove first element</button>
- Finally, we add a button to clear all elements:
<button onClick={() => clear()}>clear elements</button>
</div>
)
}
As we can see, using the useArray Hook makes dealing with arrays much simpler.