Skip to content

このページは翻訳の準備中のため、英語の原文を表示しています。

useSet

A React hook that manages a Set as state. Provides efficient state management and stable action functions.

Interface

ts
function useSet<T>(initialState: SetOrValues<T> = new Set()): UseSetReturn<T>;

Parameters

  • initialStateSetOrValues<T>

    Initial Set state (Set object or array of values).

Return Value

  • UseSetReturn<T>

    tuple containing the Set state and actions to manipulate it.

    • [0]Omit<Set<T>, 'add' | 'clear' | 'delete'>

      The current Set state with mutation methods hidden.

    • [1].add(value: T) => void

      Adds a value to the set.

    • [1].remove(value: T) => void

      Removes a value from the set.

    • [1].toggle(value: T) => void

      Adds the value if absent, removes it if present.

    • [1].setAll(values: Set<T> | T[]) => void

      Replaces all values in the set.

    • [1].reset() => void

      Resets the set to its initial state.

Example

tsx
import { useSet } from 'react-simplikit';

function TagSelector() {
  const [selectedTags, { add, remove, toggle }] = useSet<string>(['react']);

  return (
    <div>
      {['react', 'vue', 'svelte'].map(tag => (
        <button key={tag} onClick={() => toggle(tag)}>
          {selectedTags.has(tag) ? '✓' : ''} {tag}
        </button>
      ))}
    </div>
  );
}

MIT ライセンスの下で配布されています。