Skip to content

Modernize library

Use react hooks.

Typescript version:

import React, { useEffect, memo } from 'react';
import { useThrottle } from '@react-hook/throttle';

function throttledComponent<T extends Record<string, any>>(
  component: React.FC<T>,
  fps: number,
) {
  const Y = memo<T>(component);

  const Wrapped = (props: T) => {
    const [value, setValue] = useThrottle(props, fps);

    useEffect(() => {
      setValue(props);
    }, [props, setValue]);

    return <Y {...value} />;
  };

  Wrapped.displayName = `Throttled(${component.displayName || component.name})`;

  return Wrapped;
}

export default throttledComponent;