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
| Name | Type | Description |
|---|---|---|
| initialValue | any | The initial value of the state returned from useDefault. |
| defaultValue | any | The default value to be used if the state is undefined or null. |
Return Values
| Name | Type | Description |
|---|---|---|
| state | any | The current state. If the state is undefined or null, defaultValue is returned instead. |
| setState | function | The 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 defaultUsage
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>
)
}