Dashboard sipadu mbip
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

useAnimationFrame.js 1.3KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. import { useRef } from 'react';
  2. import useMounted from './useMounted';
  3. import useStableMemo from './useStableMemo';
  4. import useWillUnmount from './useWillUnmount';
  5. /**
  6. * Returns a controller object for requesting and cancelling an animation freame that is properly cleaned up
  7. * once the component unmounts. New requests cancel and replace existing ones.
  8. *
  9. * ```ts
  10. * const [style, setStyle] = useState({});
  11. * const animationFrame = useAnimationFrame();
  12. *
  13. * const handleMouseMove = (e) => {
  14. * animationFrame.request(() => {
  15. * setStyle({ top: e.clientY, left: e.clientY })
  16. * })
  17. * }
  18. *
  19. * const handleMouseUp = () => {
  20. * animationFrame.cancel()
  21. * }
  22. *
  23. * return (
  24. * <div onMouseUp={handleMouseUp} onMouseMove={handleMouseMove}>
  25. * <Ball style={style} />
  26. * </div>
  27. * )
  28. * ```
  29. */
  30. export default function useAnimationFrame() {
  31. var isMounted = useMounted();
  32. var handle = useRef();
  33. var cancel = function cancel() {
  34. if (handle.current != null) {
  35. cancelAnimationFrame(handle.current);
  36. }
  37. };
  38. useWillUnmount(cancel);
  39. return useStableMemo(function () {
  40. return {
  41. request: function request(cancelPrevious, fn) {
  42. if (!isMounted()) return;
  43. if (cancelPrevious) cancel();
  44. handle.current = requestAnimationFrame(fn || cancelPrevious);
  45. },
  46. cancel: cancel
  47. };
  48. }, []);
  49. }