use-motion-ref.mjs 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { useCallback } from 'react';
  2. import { isRefObject } from '../../utils/is-ref-object.mjs';
  3. /**
  4. * Creates a ref function that, when called, hydrates the provided
  5. * external ref and VisualElement.
  6. */
  7. function useMotionRef(visualState, visualElement, externalRef) {
  8. return useCallback((instance) => {
  9. if (instance) {
  10. visualState.onMount && visualState.onMount(instance);
  11. }
  12. if (visualElement) {
  13. if (instance) {
  14. visualElement.mount(instance);
  15. }
  16. else {
  17. visualElement.unmount();
  18. }
  19. }
  20. if (externalRef) {
  21. if (typeof externalRef === "function") {
  22. externalRef(instance);
  23. }
  24. else if (isRefObject(externalRef)) {
  25. externalRef.current = instance;
  26. }
  27. }
  28. },
  29. /**
  30. * Only pass a new ref callback to React if we've received a visual element
  31. * factory. Otherwise we'll be mounting/remounting every time externalRef
  32. * or other dependencies change.
  33. */
  34. [visualElement]);
  35. }
  36. export { useMotionRef };