usePressability.js 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243
  1. /**
  2. * Copyright (c) Facebook, Inc. and its affiliates.
  3. *
  4. * This source code is licensed under the MIT license found in the
  5. * LICENSE file in the root directory of this source tree.
  6. *
  7. * @flow strict-local
  8. * @format
  9. */
  10. 'use strict';
  11. import Pressability, {
  12. type EventHandlers,
  13. type PressabilityConfig,
  14. } from './Pressability';
  15. import {useEffect, useRef} from 'react';
  16. export default function usePressability(
  17. config: PressabilityConfig,
  18. ): EventHandlers {
  19. const pressabilityRef = useRef<?Pressability>(null);
  20. if (pressabilityRef.current == null) {
  21. pressabilityRef.current = new Pressability(config);
  22. }
  23. const pressability = pressabilityRef.current;
  24. // On the initial mount, this is a no-op. On updates, `pressability` will be
  25. // re-configured to use the new configuration.
  26. useEffect(() => {
  27. pressability.configure(config);
  28. }, [config, pressability]);
  29. // On unmount, reset pending state and timers inside `pressability`. This is
  30. // a separate effect because we do not want to reset when `config` changes.
  31. useEffect(() => {
  32. return () => {
  33. pressability.reset();
  34. };
  35. }, [pressability]);
  36. return pressability.getEventHandlers();
  37. }