useGetState
State plus a getter that always returns the latest value.
State plus a getter that always returns the latest value.
Import
import { useGetState } from '@kamod-ch/hooks'Live demo
Basic demo
State plus a getter that always returns the latest value.
Getter result: fresh state
import { useGetState } from '@kamod-ch/hooks'
export default function UseGetStateDemo() {
const [value, setValue, getValue] = useGetState('fresh state')
return (
<div>
<label>
Value
<input value={value} onInput={(event) => setValue(event.currentTarget.value)} />
</label>
<p><strong>Getter result:</strong> {getValue()}</p>
</div>
)
}
API
TypeScript signature
import type { Dispatch, SetStateAction } from '../utils/types-compat.js';
type GetStateAction<S> = () => S;
declare function useGetState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>, GetStateAction<S>];
declare function useGetState<S = undefined>(): [
S | undefined,
Dispatch<SetStateAction<S | undefined>>,
GetStateAction<S | undefined>
];
export default useGetState;
/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.