Skip to main content

useRafState

React state hook that only updates state in the callback of requestAnimationFrame

Usage

Live Editor
function Demo() {
  const [state, setState] = useRafState({ x: 0, y: 0 });

  useMount(() => {
    const onMouseMove = (event: MouseEvent) => {
      setState({ x: event.clientX, y: event.clientY });
    };
    const onTouchMove = (event: TouchEvent) => {
      setState({
        x: event.changedTouches[0].clientX,
        y: event.changedTouches[0].clientY,
      });
    };

    document.addEventListener("mousemove", onMouseMove);
    document.addEventListener("touchmove", onTouchMove);

    return () => {
      document.removeEventListener("mousemove", onMouseMove);
      document.removeEventListener("touchmove", onTouchMove);
    };
  });

  return <pre>{JSON.stringify(state, null, 2)}</pre>;
};

Result
Loading...

API

useRafState

Returns

readonly [S, React.Dispatch<React.SetStateAction<S>>]: A tuple with the following elements:

  • the state value
  • a function to update state in requestAnimationFrame

Arguments

ArgumentDescriptionTypeDefaultValue
initialStatestate valueS | (() => S) (Required)-