State Hooks
useControllableState, useToggle, usePrevious, useLatest, useLocalStorage.
useControllableState
Unified controlled/uncontrolled state pattern. When value is provided, the component is controlled. When value is undefined, internal state is used.
import { useControllableState } from '@vitus-labs/hooks'
function Input({ value, defaultValue = '', onChange }) {
const [state, setState] = useControllableState({
value,
defaultValue,
onChange,
})
return <input value={state} onChange={(e) => setState(e.target.value)} />
}
// Uncontrolled
<Input defaultValue="hello" onChange={(v) => console.log(v)} />
// Controlled
<Input value={controlledValue} onChange={setControlledValue} />Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | undefined | Controlled value (if provided, component is controlled) |
defaultValue | T | Initial value when uncontrolled |
onChange | (value: T) => void | Callback fired on every value change |
Returns
[T, (next: T | ((prev: T) => T)) => void] — state value and setter function.
The setter accepts either a direct value or an updater function (like useState). Consecutive functional updates in the same event (setValue(p => p + 1) twice) compute from the latest value, in both controlled and uncontrolled mode. onChange fires in both modes.
useToggle
Boolean state with convenience methods. All callbacks are memoized and stable across rerenders.
import { useToggle } from '@vitus-labs/hooks'
function Modal() {
const [isOpen, toggle, open, close] = useToggle(false)
return (
<>
<button onClick={toggle}>Toggle</button>
<button onClick={open}>Open</button>
{isOpen && (
<div>
Modal content
<button onClick={close}>Close</button>
</div>
)}
</>
)
}Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | boolean | false | Initial boolean value |
Returns
[boolean, () => void, () => void, () => void]
| Index | Name | Description |
|---|---|---|
| 0 | value | Current boolean state |
| 1 | toggle | Flip the value |
| 2 | setTrue | Set to true |
| 3 | setFalse | Set to false |
usePrevious
Returns the value from the previous render. Returns undefined on the first render.
import { usePrevious } from '@vitus-labs/hooks'
function Counter({ count }) {
const prevCount = usePrevious(count)
return (
<div>
Current: {count}, Previous: {prevCount ?? 'none'}
{prevCount !== undefined && count > prevCount && ' (increased)'}
</div>
)
}Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | Any value to track |
Returns
T | undefined — value from the previous render.
useLatest
Returns a ref that always holds the latest value. Useful to avoid stale closures in callbacks and effects without adding the value to dependency arrays.
import { useLatest } from '@vitus-labs/hooks'
function SearchInput({ onSearch }) {
const onSearchRef = useLatest(onSearch)
const debouncedSearch = useMemo(
() => debounce((query) => {
onSearchRef.current(query) // Always calls the latest onSearch
}, 300),
[] // No deps needed — ref always current
)
return <input onChange={(e) => debouncedSearch(e.target.value)} />
}Parameters
| Parameter | Type | Description |
|---|---|---|
value | T | Any value |
Returns
{ readonly current: T } — ref object with latest value.
useLocalStorage
State synced with localStorage. SSR-safe, hydration-safe, and tolerant of private-mode / quota-exceeded errors.
import { useLocalStorage } from '@vitus-labs/hooks'
function ThemeSwitcher() {
const [theme, setTheme, clearTheme] = useLocalStorage('theme', 'light')
return (
<>
<button onClick={() => setTheme((t) => (t === 'light' ? 'dark' : 'light'))}>
Theme: {theme}
</button>
<button onClick={clearTheme}>Reset</button>
</>
)
}Parameters
| Parameter | Type | Description |
|---|---|---|
key | string | Storage key |
initialValue | T | Value used when the key is missing, on the server, and during hydration |
Returns
[T, (value: T | ((prev: T) => T)) => void, () => void]
| Index | Name | Description |
|---|---|---|
| 0 | value | Current value (parsed from JSON) |
| 1 | setValue | Write a new value or an updater function; serialized with JSON.stringify |
| 2 | remove | Remove the entry and reset the value to initialValue |
Behavior
- Hydration-safe (2.9) — built on
useSyncExternalStore. The server and the hydrating client renderinitialValue, then React re-renders with the stored value straight after hydration, so there is no hydration mismatch. Client-only renders read storage on the first render. - Synced — every instance using the same key stays in sync, within the tab and across tabs (via the
storageevent). - Fault-tolerant — if a write fails (private mode, quota exceeded), the value is kept in memory and still shared between same-key instances. A malformed stored entry falls back to the last good value (or
initialValue). setValueandremoveare no-ops on the server. Callback identities are stable; an inline-objectinitialValuedoes not cause re-subscription.- Web only — not exported on React Native.
Last updated on