use-state-history

Move back/forward in state history

Import

Usage

useStateHistory hook is used to create a state with history, it returns current value, handlers to go back/forward and a history object with all previous values and current index.

Current value: 1

{
  "history": [
    1
  ],
  "current": 0
}
import { Button, Code, Group, Text } from '@mantine/core';
import { useStateHistory } from '@mantine/hooks';

function Demo() {
  const [value, handlers, history] = useStateHistory(1);
  return (
    <>
      <Text>Current value: {value}</Text>
      <Group my="md">
        <Button onClick={() => handlers.set(Math.ceil(Math.random() * 100) + 1)}>Set value</Button>
        <Button onClick={() => handlers.back()}>Back</Button>
        <Button onClick={() => handlers.forward()}>Forward</Button>
        <Button onClick={() => handlers.reset()}>Reset</Button>
      </Group>
      <Code block>{JSON.stringify(history, null, 2)}</Code>
    </>
  );
}

Definition

UseStateHistoryHandlers and StateHistory interfaces are exported from @mantine/hooks package.

interface UseStateHistoryHandlers<T> {
  set: (value: T) => void;
  back: (steps?: number) => void;
  forward: (steps?: number) => void;
  reset: () => void;
}

interface StateHistory<T> {
  history: T[];
  current: number;
}

function useStateHistory<T>(
  initialValue: T
): [T, UseStateHistoryHandlers<T>, StateHistory<T>];