use-motion-value.mjs 1.2 KB

1234567891011121314151617181920212223242526272829303132333435363738
  1. import { motionValue } from 'motion-dom';
  2. import { useContext, useState, useEffect } from 'react';
  3. import { MotionConfigContext } from '../context/MotionConfigContext.mjs';
  4. import { useConstant } from '../utils/use-constant.mjs';
  5. /**
  6. * Creates a `MotionValue` to track the state and velocity of a value.
  7. *
  8. * Usually, these are created automatically. For advanced use-cases, like use with `useTransform`, you can create `MotionValue`s externally and pass them into the animated component via the `style` prop.
  9. *
  10. * ```jsx
  11. * export const MyComponent = () => {
  12. * const scale = useMotionValue(1)
  13. *
  14. * return <motion.div style={{ scale }} />
  15. * }
  16. * ```
  17. *
  18. * @param initial - The initial state.
  19. *
  20. * @public
  21. */
  22. function useMotionValue(initial) {
  23. const value = useConstant(() => motionValue(initial));
  24. /**
  25. * If this motion value is being used in static mode, like on
  26. * the Framer canvas, force components to rerender when the motion
  27. * value is updated.
  28. */
  29. const { isStatic } = useContext(MotionConfigContext);
  30. if (isStatic) {
  31. const [, setLatest] = useState(initial);
  32. useEffect(() => value.on("change", setLatest), []);
  33. }
  34. return value;
  35. }
  36. export { useMotionValue };