Docs
Default

Default

Manage state with default values.

About

The useDefault hook works similarly to useState but with a key difference: if the state of the hook is undefined or null, useDefault will set the state to a provided default value.

Parameters

NameTypeDescription
initialValueanyThe initial value of the state returned from useDefault.
defaultValueanyThe default value to be used if the state is undefined or null.

Return Values

NameTypeDescription
stateanyThe current state. If the state is undefined or null, defaultValue is returned instead.
setStatefunctionThe state setter function returned from React.useState(). This can be called to update the state.

Installation

Run the following command:

npx scriptkavi-hooks@latest add default

Usage

import { useDefault } from "@/hooks/default"
import * as React from "react"
 
export default function App() {
  const initialState = { name: "Tyler" }
  const defaultState = { name: "Ben" }
 
  const [user, setUser] = useDefault(initialState, defaultState)
 
  return (
    <section>
      <h1>useDefault</h1>
 
      <button
        title="Sets the value to Lynn"
        className="link"
        onClick={() => setUser({ name: "Lynn" })}
      >
        Lynn
      </button>
      <button
        title="Sets the value to Tyler"
        className="link"
        onClick={() => setUser({ name: "Tyler" })}
      >
        Tyler
      </button>
      <button
        title="Sets the value to null causing it to use the default value"
        className="link"
        onClick={() => setUser(null)}
      >
        Null
      </button>
      <pre>
        <code>{JSON.stringify(user)}</code>
      </pre>
    </section>
  )
}