Skip to main content

Usage

import { useListState } from '@kivora/react';

function TodoList() {
  const [items, handlers] = useListState(['Buy milk', 'Walk dog']);

  return (
    <div>
      {items.map((item, index) => (
        <div key={index}>
          <span>{item}</span>
          <button onClick={() => handlers.remove(index)}>Remove</button>
        </div>
      ))}
      <button onClick={() => handlers.append('New task')}>Add Task</button>
    </div>
  );
}

Parameters

initialValue
T[]
default:"[]"
Initial array value

Return Value

Returns a tuple with the current array and an object of mutation handlers:
[0]
T[]
Current array state
[1]
UseListStateHandlers<T>
Mutation handlers

Examples

Managing a Todo List

const [todos, handlers] = useListState([
  { id: 1, text: 'Learn React', done: false },
  { id: 2, text: 'Build app', done: false }
]);

// Add new todo
handlers.append({ id: 3, text: 'Deploy', done: false });

// Remove completed todos
handlers.filter((todo) => !todo.done);

// Mark todo as done
handlers.setItem(0, { ...todos[0], done: true });

Drag and Drop Reordering

const [items, handlers] = useListState(['A', 'B', 'C', 'D']);

const onDragEnd = (result) => {
  if (!result.destination) return;
  handlers.reorder(result.source.index, result.destination.index);
};

Form Fields Array

const [fields, handlers] = useListState([{ name: '', email: '' }]);

return (
  <div>
    {fields.map((field, index) => (
      <div key={index}>
        <input
          value={field.name}
          onChange={(e) => handlers.setItem(index, { ...field, name: e.target.value })}
        />
        <button onClick={() => handlers.remove(index)}>Remove</button>
      </div>
    ))}
    <button onClick={() => handlers.append({ name: '', email: '' })}>
      Add Field
    </button>
  </div>
);

Insert at Position

const [list, handlers] = useListState([1, 2, 4, 5]);

// Insert 3 at index 2
handlers.insert(2, 3); // [1, 2, 3, 4, 5]

Build docs developers (and LLMs) love