Typed HooksGetting StarteduseDefault

useDefault

A custom React hook that manages a stateful value with a default fallback.

useDefault is a helpful custom React hook designed to manage stateful values with a default fallback when the value is set to null or undefined.

This hook is particularly useful when you need to maintain state values that might be reset or cleared, but should fall back to a predefined default rather than being null or undefined.

Current value
10

Initial: 10 | Default: 0 | Custom: 5

Note: When setting to null or undefined, the hook automatically falls back to the default value (0).

Installation

pnpm dlx shadcn@latest add https://shaddy-docs.vercel.app/r/use-default

API

useDefault(initialValue, defaultValue): [T, (newValue: Nullable<T>) => void]

NameTypeRequiredDescription
initialValueTYesThe initial value of the state.
defaultValueTYesThe fallback value when state is null or undefined.

Returns [value, setValue]:

  • value (T): The current state value.
  • setValue (function): A function that updates the state value. If called with null or undefined, it will use the default value instead.