Skip to Content
vitus·labs
Hooks

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

ParameterTypeDescription
valueT | undefinedControlled value (if provided, component is controlled)
defaultValueTInitial value when uncontrolled
onChange(value: T) => voidCallback 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

ParameterTypeDefaultDescription
initialValuebooleanfalseInitial boolean value

Returns

[boolean, () => void, () => void, () => void]

IndexNameDescription
0valueCurrent boolean state
1toggleFlip the value
2setTrueSet to true
3setFalseSet 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

ParameterTypeDescription
valueTAny 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

ParameterTypeDescription
valueTAny 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

ParameterTypeDescription
keystringStorage key
initialValueTValue used when the key is missing, on the server, and during hydration

Returns

[T, (value: T | ((prev: T) => T)) => void, () => void]

IndexNameDescription
0valueCurrent value (parsed from JSON)
1setValueWrite a new value or an updater function; serialized with JSON.stringify
2removeRemove the entry and reset the value to initialValue

Behavior

  • Hydration-safe (2.9) — built on useSyncExternalStore. The server and the hydrating client render initialValue, 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 storage event).
  • 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).
  • setValue and remove are no-ops on the server. Callback identities are stable; an inline-object initialValue does not cause re-subscription.
  • Web only — not exported on React Native.
Edit on GitHub

Last updated on

On this page