Skip to content

useSafeState

Category
Export Size
194 B
Last Changed
5 days ago

A useState whose setter is a no-op once the component has unmounted.

Demo

Usage

tsx
import { 
useSafeState
} from '@reause/shared'
const [
value
,
setValue
] =
useSafeState
(0)
async function
load
() {
const
data
= await fetchData()
// ignored if the component unmounted while the request was in flight
setValue
(
data
)
}

Type Declarations

ts
export function useSafeState<S>(initialState: S | (() => S)): [
    S,
    Dispatch<SetStateAction<S>>
]

export function useSafeState<S = undefined>(): [
    S | undefined,
    Dispatch<SetStateAction<S | undefined>>
]

Source

Source · Demo · ahooks

Contributors

hairyf

Changelog

v0.1.7 on
2395d - feat(shared): add useSafeState (#944)

Released under the MIT License. v0.1.8