The useArray Hook

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:

  1. First, we import the useArray Hook from react-hookedup:
import React from 'react'
import { useArray } from 'react-hookedup'
  1. 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'])
  1. Now, we display the current array as JSON:
    return (
<div>
<p>current array: {JSON.stringify(value)}</p>
  1. Then, we display a button to add an element:
            <button onClick={() => add('test')}>add element</button>
  1. Next, we display a button to remove the first element by index:
            <button onClick={() => removeIndex(0)}>remove first element</button>
  1. 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.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.144.97.189