Docs
Set

Set

Synchronize and update state based on the Set data structure

About

The useSet hook manages and manipulates the Set data structure within a React component. It provides a way to create and maintain a set of values, with custom methods like “add,” “clear,” and “delete.” The hook updates and tracks changes to the set, triggering re-renders whenever modifications occur.

Parameters

NameTypeDescription
valuesarray(Optional) Initial values for the set.

Return Values

NameTypeDescription
setsetAn instance of the Set object with enhanced methods.

Installation

Run the following command:

npx scriptkavi-hooks@latest add set

Usage

import { useSet } from "@/hooks/set"
import * as React from "react"
 
function format(val) {
  return val.toLocaleLowerCase().replace(/\s/g, "")
}
 
export default function App() {
  const [value, setValue] = React.useState("")
  const set = useSet([
    "benadam11",
    "tylermcginnis",
    "lynnandtonic",
    "alexbrown40",
    "hooksdotscriptkavi",
    "vedvyasdotio",
    "reactnewsletter",
  ])
 
  const handleSubmit = (e) => {
    e.preventDefault()
    const formData = new FormData(e.target)
    const username = formData.get("username")
    set.add(format(username))
    setValue("")
    e.target.reset()
    e.target.focus()
  }
 
  const hasError = set.has(value)
 
  return (
    <section>
      <h1>useSet</h1>
      <p>Check if your username is available</p>
      <article>
        <form className={hasError ? "error" : ""} onSubmit={handleSubmit}>
          <span>@</span>
          <input
            type="text"
            name="username"
            placeholder="Enter a username"
            onChange={(e) => {
              setValue(format(e.target.value))
            }}
          />
        </form>
        {hasError && <label>Woops that user is taken</label>}
      </article>
 
      <table>
        <tbody>
          {Array.from(set.values()).map((username) => {
            const match = username === value
            return (
              <tr key={username}>
                <th>username</th>
                <td
                  style={{
                    borderColor: match ? "var(--red)" : "var(--charcoal)",
                  }}
                >
                  {username}
                </td>
              </tr>
            )
          })}
        </tbody>
      </table>
    </section>
  )
}