Skip to content

useStateDefault

Category
Export Size
360 B
Last Changed
5 days ago

Apply default value to a ref

Demo

Usage

tsx
import { 
useStateDefault
} from '@reause/shared'
const
raw
= {
current
:
undefined
as string | undefined }
const [
value
,
setValue
] =
useStateDefault
(
raw
, 'default')
setValue
('hello')
// the derived value updates on the next render (React derives it at render)
console
.
log
(
value
) // 'hello' after the next render
console
.
log
(
raw
.
current
) // 'hello' (written through immediately)
setValue
(
undefined
)
console
.
log
(
value
) // 'default' after the next render
raw
.
current
= 'from outside' // external control — picked up on the next render

Type Declarations

ts
export type UseStateDefaultReturn<T = any> = [
    value: T,
    setValue: Dispatch<SetStateAction<T | undefined | null>>
]

export type State<T> = StateValue<T>

export function useStateDefault<T = any>(source: State<T | undefined | null>, defaultValue: T): UseStateDefaultReturn<T>

export function useControllableState<T>(state: State<T>, options?: UseControllableStateOptions<T>): StateTuple<T>

Source

Source · Demo · VueUse

Contributors

hairyf

Changelog

v0.1.0 on
c1c4c - fix(shared): resolve useStateDefault audit findings (#744)
e94bf - feat(shared): add useStateDefault (#51)

Released under the MIT License. v0.1.8