state

React custom hooks for handling structure(array) with normal state or recoil state

Sep 27, 2021
React custom hooks for handling structure(array) with normal state or recoil state

React Structured State

React custom hooks for handling structure(array) with normal state or recoil state.

Install

$ npm install react-structured-state

View Demo View Github

How to use

Define

with normal(react hooks) state

import { useArray } from 'react-structured-state'; const App = (): JSX.Element => { const [arr, actionArr] = useArray<number>([1, 2, 3]); return ( ... ) }

with recoil state

import { atom } from 'recoil'; import { useRecoilArray } from 'react-structured-state'; export const arrayState = atom({ key: 'arrayState', default: [1, 2, 3], }); const App = (): JSX.Element => { const [arr, actionArr] = useRecoilArray<number>(arrayState); return ( ... ) }

Use Case

push 10 to back

// Before setArr((oldarr) => [...oldarr, 10]); // After actionArr.pushBack(10);

double all elements

// Before setArr((oldarr) => oldarr.map((e) => e * 2)); // After actionArr.map((e) => e * 2);

Example

useArray<T> / useRecoilArray<T> return two values.

First value is Array<T> used for view array elements.

Second value is object of action like array methods (map, filter, ...). This is used for change value.

API

methodactionargsargs(optional)default
setStatebasic setStateT[]
pushBackadd value(s) on backval: T... vals: T[]none
pushFrontadd value(s) on frontval: T,...vals: T[]none
insertinsert valueidx: number, val: T...vals: T[]none
popBackremove value(s) on backcount: number1
popFrontremove value(s) on frontcount: number1
concatBackadd elements of array on backvals: T[]
concatFrontadd elements of array on frontvals: T[]
sortsort with callbackfn: (vals: T[]) => T[](a, b) => a - b
reversereverse elements
sliceupdate values with slice()start:number, end:number0, length
spliceupdate values with splice()start:numberdeleteCount: number, ...vals: T[]none, none
filterupdate values with filter()fn:(vals: T[]) => boolean
mapupdate values with map()fn:(vals: T[]) => T[]
fillupdate values with fill()val: Tstart: number, end:number0, length
chainupdate vlues with array method chainfn: (vals:T[]) => T[]
setset value on specified indexidx:number, val: T
eraseerase element by specified valueval:T
clearclear all elements
Recommended