Skip to content

Instantly share code, notes, and snippets.

@jhavenz
Last active April 3, 2023 03:52
Show Gist options
  • Save jhavenz/07c4436823118d527d3584924ef3d7f9 to your computer and use it in GitHub Desktop.
Save jhavenz/07c4436823118d527d3584924ef3d7f9 to your computer and use it in GitHub Desktop.
useArray React Hook
import React, { useState } from 'react'
export default function useArray(defaultValue) {
const [array, setArray] = useState(defaultValue)
function push(element) {
setArray((a) => [...a, element])
}
function filter(callback) {
setArray((a) => a.filter(callback))
}
function updateArray(index, newEl) {
array.splice()
setArray((a) => [
...a.slice(0, index),
newEl,
...a.slice(index + 1, a.length - 1),
])
}
function remove(index) {
setArray((a) => [
...a.slice(0, index),
...a.slice(index + 1, a.length - 1),
])
}
function clear() {
setArray([])
}
return {
array,
set: setArray,
push,
filter,
update: updateArray,
remove,
clear,
}
}
import React from 'react'
export default function UseArrayExampleComponent() {
const { array, set, push, remove, filter, update, clear } = useArray([
1, 2, 3, 4, 5, 6,
])
return (
<div>
<div>{array.join(', ')}</div>
<button onClick={() => push(7)}>Add 7</button>
<button onClick={() => update(1, 9)}>
Change Second Element to 9
</button>
<button onClick={() => remove(1)}>Remove Second Element</button>
<button onClick={() => filter((n) => n < 3)}>
Keep Number Less than 4
</button>
<button onClick={() => set([1, 2])}>Set to 1, 2</button>
<button onClick={clear}>Clear</button>
</div>
)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment