React Custom Hook: useArray

react-custom-hook: usearray

In this article series, we embark on a journey through the realm of custom React hooks, discovering their immense potential for elevating your development projects. Our focus today is on the “useArray” hook, one of the many carefully crafted hooks available in the collection of React custom hooks.

Github: https://github.com/sergeyleschev/react-custom-hooks

import { 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 update(index, newElement) {
        setArray(a => [
            ...a.slice(0, index),
            newElement,
            ...a.slice(index + 1, a.length),
        ])
    }

    function remove(index) {
        setArray(a => [...a.slice(0, index), ...a.slice(index + 1, a.length)])
    }

    function clear() {
        setArray([])
    }

    return { array, set: setArray, push, filter, update, remove, clear }
}

The useArray hook utilizes the useState hook from React to initialize and manage the array state. It returns an object with the following functions:

  • push(element): Adds the specified element to the array.
  • filter(callback): Filters the array based on the provided callback function, removing elements that don’t satisfy the condition.
  • update(index, newElement): Replaces the element at the specified index with the newElement.
  • remove(index): Removes the element at the specified index from the array.
  • clear(): Clears the array, setting it to an empty array.

The advantages of using this custom hook are twofold: it simplifies the management of array states and provides a cleaner and more readable code structure. With the useArray hook, you can easily add, update, remove, filter, and clear elements in an array without dealing with complex logic.

import useArray from "./useArray"

export default function ArrayComponent() {
    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 Numbers Less Than 4
            </button>
            <button onClick={() => set([1, 2])}>Set To 1, 2</button>
            <button onClick={clear}>Clear</button>
        </div>
    )
}

Throughout this article series, we focused on one of the gems from the collection of React custom hooks  “useArray“. This hook, sourced from the “react-custom-hooks” repository, revolutionizes how we work with arrays in our React applications.

Full Version | React Custom Hooks:
https://dev.to/sergeyleschev/supercharge-your-react-projects-with-custom-hooks-pl4

Total
0
Shares
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Post
the-complete-guide-to-becoming-a-web-developer:-part-6

The Complete Guide to Becoming a Web Developer: Part 6

Next Post
mastering-javascript-shorthand-techniques:-code-faster-and-cleaner-part-2

Mastering JavaScript Shorthand Techniques: Code Faster and Cleaner Part 2

Related Posts

網紅程式設計師回應炒股一年虧130萬:當流量主體走進散戶敘事,虧損也成了內容

一位擁有技術背景的網紅程式設計師公開承認一年在股市虧損約130萬人民幣並回應爭議。本文拆解事件經過、散戶在高波動市場的結構性劣勢,以及科技自媒體與投資敘事的邊界。 Techroomage 編輯部 · 2026年7月1日 · 閱讀約 8 分鐘 一年虧掉130萬。當這個數字出現在一個以理性、技術背景為人設的網紅程式設計師身上,它不再是單純的帳面損失,而變成了一則被演算法與留言區共同咀嚼的內容事件。微博熱搜「網紅程式設計師回應炒股1年虧130萬」之所以快速發酵,在於它踩中了一個尷尬的對比:一個理論上最懂數據、最擅長建立模型的羣體,在公開市場裡依然難以免疫散戶的宿命。 TL;DR 一位在微博具有相當關注度的網紅程式設計師公開回應「炒股一年虧損約130萬人民幣」的傳聞,承認虧損屬實並對外說明。事件折射出科技自媒體人物把個人投資經歷內容化的新趨勢,也再次暴露散戶在高波動市場中的資訊劣勢與情緒管理難題。 事件經過 熱搜話題源於這位程式設計師在社羣平臺上揭露自己過去一年累計虧損約130萬人民幣的紀錄,隨後引發大量轉發與討論。當事人隨後親自下場回應,針對外界質疑做出說明。 需要強調的是,130萬這個數字來自當事人自述與微博話題傳播,並未經第三方財報或券商資料獨立核實;其部位結構(個股、ETF、是否含融資槓桿)也未有完整公開。引用時應保留這層不確定性,避免把自述數字當成可查證的財務事實。 關鍵事實(條列) 事件主角:一位在中國社羣平臺具有技術人設、被網友稱為「網紅程式設計師」的內容創作者 關鍵數字:自述一年累計虧損約130萬人民幣(來源為當事人公開發言,未經獨立核實)…
Read More