Docs
Object State

Object State

Manage complex state objects

About

The useObjectState hook manages complex state objects, providing a convenient way to initialize and update state values using a single hook. It allows easy creation and maintenance of state objects with initial values and includes a flexible “handleUpdate” function to merge new values into the existing state object.

Parameters

NameTypeDescription
initialValueobject(Optional) The initial state value.

Return Values

IndexTypeDescription
0objectThe current state object.
1functionA function to update the state object.

Installation

Run the following command:

npx scriptkavi-hooks@latest add object-state

Usage

import { useObjectState } from "@/hooks/object-state"
import * as React from "react"
 
const initialState = {
  team: "Utah Jazz",
  wins: 2138,
  losses: 1789,
  championships: 0,
}
 
export default function App() {
  const [stats, setStats] = useObjectState(initialState)
 
  const addWin = () => {
    setStats((s) => ({
      wins: s.wins + 1,
    }))
  }
 
  const addLoss = () => {
    setStats((s) => ({
      losses: s.losses + 1,
    }))
  }
 
  const reset = () => {
    setStats(initialState)
  }
 
  return (
    <section>
      <h1>useObjectState</h1>
 
      <button className="link" onClick={addWin}>
        Add Win
      </button>
      <button className="link" onClick={addLoss}>
        Add Loss
      </button>
 
      <button className="link" onClick={() => alert("lol")}>
        Add Championship
      </button>
      <button className="link" onClick={reset}>
        Reset
      </button>
 
      <table>
        <thead>
          <tr>
            {Object.keys(stats).map((key) => {
              return <th>{key}</th>
            })}
          </tr>
        </thead>
        <tbody>
          <tr>
            {Object.keys(stats).map((key) => {
              return <td>{`${stats[key]}`}</td>
            })}
          </tr>
        </tbody>
      </table>
    </section>
  )
}