Skip to content

useDynamicList

Mutable-feeling list helpers for insert, remove, move, and reset.

Mutable-feeling list helpers for insert, remove, move, and reset.

Import

import { useDynamicList } from '@kamod-ch/hooks'

Live demo

Basic demo

Mutable-feeling list helpers for insert, remove, move, and reset.

  1. alpha
  2. beta
  3. gamma
import { useDynamicList } from '@kamod-ch/hooks'

export default function UseDynamicListDemo() {
  const list = useDynamicList(['alpha', 'beta', 'gamma'])

  return (
    <div>
      <ol>{list.list.map((item, index) => <li key={list.getKey(index)}>{item}</li>)}</ol>
      <div class="demo-actions">
        <button type="button" onClick={() => list.push('delta')}>Push</button>
        <button type="button" onClick={() => list.remove(1)}>Remove second</button>
        <button type="button" onClick={() => list.move(0, list.list.length - 1)}>Move first to last</button>
        <button type="button" onClick={() => list.resetList(['alpha', 'beta', 'gamma'])}>Reset</button>
      </div>
    </div>
  )
}

API

TypeScript signature
declare const useDynamicList: <T>(initialList?: T[]) => {
    list: T[];
    insert: (index: number, item: T) => void;
    merge: (index: number, items: T[]) => void;
    replace: (index: number, item: T) => void;
    remove: (index: number) => void;
    batchRemove: (indexes: number[]) => void;
    getKey: (index: number) => number;
    getIndex: (key: number) => number;
    move: (oldIndex: number, newIndex: number) => void;
    push: (item: T) => void;
    pop: () => void;
    unshift: (item: T) => void;
    shift: () => void;
    sortList: (result: T[]) => T[];
    resetList: (newList: T[]) => void;
};
export default useDynamicList;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.