useSafeState
State setter that no-ops after unmount.
State setter that no-ops after unmount.
Import
import { useSafeState } from '@kamod-ch/hooks'Live demo
Basic demo
State setter that no-ops after unmount.
Status: waiting
import { useState } from 'preact/hooks'
import { useSafeState } from '@kamod-ch/hooks'
function Child() {
const [value, setValue] = useSafeState('waiting')
return (
<div>
<p><strong>Status:</strong> {value}</p>
<button type="button" onClick={() => {
setValue('loading')
window.setTimeout(() => setValue('resolved safely'), 800)
}}>Start async update</button>
</div>
)
}
export default function UseSafeStateDemo() {
const [visible, setVisible] = useState(true)
return (
<div>
<button type="button" onClick={() => setVisible((value) => !value)}>{visible ? 'Unmount child' : 'Mount child'}</button>
{visible ? <Child /> : <p>Child removed before late updates can land.</p>}
</div>
)
}
API
TypeScript signature
import type { Dispatch, SetStateAction } from '../utils/types-compat.js';
declare function useSafeState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
declare function useSafeState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
export default useSafeState;
/SSR considerations
This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.
Browser compatibility
Works in any modern browser supported by Preact.