Skip to content

このページは翻訳の準備中のため、英語の原文を表示しています。

useThrottledValue

useThrottledValue is a React hook that returns a throttled copy of the given value. The caller keeps owning the state; the returned value follows it at most once per wait milliseconds, which is useful for driving expensive renders from scroll position, pointer position, or an element's size on resize.

On the first render and on the server the value is returned as is. A change is never scheduled on mount, so the first change after mount is applied immediately when leading is true. If both leading and trailing are false, the returned value never updates.

The value is compared by reference. Passing a new object or array on every render keeps the returned value updating every wait milliseconds; stabilize the reference first, for example with usePreservedReference.

Interface

ts
function useThrottledValue<T>(
  value: T,
  wait: number,
  options: ThrottleOptions
): T;

Parameters

  • valuerequired · T

    The value to throttle.

  • waitrequired · number

    The length of the throttle window in milliseconds.

  • optionsThrottleOptions

    Configuration options for throttle behavior.

    • options.leadingboolean · true

      If true, the first change in a window is applied immediately.

    • options.trailingboolean · true

      If true, the last change in a window is applied wait milliseconds after that change.

Return Value

  • T

    throttled value.

Example

tsx
import { useThrottledValue } from 'react-simplikit';
import { useState } from 'react';

function ScrollProgress() {
  const [scrollY, setScrollY] = useState(0);
  const throttledScrollY = useThrottledValue(scrollY, 100);

  return (
    <div onScroll={e => setScrollY(e.currentTarget.scrollTop)}>
      <ProgressBar position={throttledScrollY} />
    </div>
  );
}

MIT ライセンスの下で配布されています。