Skip to content

useRafState

State updates batched to the next animation frame.

State updates batched to the next animation frame.

Import

import { useRafState } from '@kamod-ch/hooks'

Live demo

Basic demo

State updates batched to the next animation frame.

Value: 0

import { useRafState } from '@kamod-ch/hooks'

export default function UseRafStateDemo() {
  const [value, setValue] = useRafState(0)

  return (
    <div>
      <p><strong>Value:</strong> {value}</p>
      <button type="button" onClick={() => { setValue((count) => count + 1); setValue((count) => count + 1) }}>Queue two RAF updates</button>
    </div>
  )
}

API

TypeScript signature
import type { Dispatch, SetStateAction } from '../utils/types-compat.js';
declare function useRafState<S>(initialState: S | (() => S)): [S, Dispatch<SetStateAction<S>>];
declare function useRafState<S = undefined>(): [S | undefined, Dispatch<SetStateAction<S | undefined>>];
export default useRafState;
/

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.