Hooks

Exploring useScroll, useTransform, useMotionValue and useMotionValueEvent hooks

Hooks are incredibly useful in Motion. If you want to track scroll progress, want to transform one value to another, watch the values change as they are updated, or just want to create a custom animation, hooks are the way to go.

There are many hooks available in Motion, but we are going to talk about the following hooks in this lesson:

  • useScroll -- Tracks scroll progress, or scroll values
  • useTransform -- Transforms one value to another
  • useMotionValue -- Creates a motion value that can be used to animate values, or watch them change
  • useMotionValueEvent -- Watches for changes in a motion value

Here's an example of how you can use useScroll and useTransform to create this scroll parallax animation

const { scrollYProgress } = useScroll({ target: containerRef });

This allows you to get to know the progress of scroll on a page between the range of 0 to 1.

You can bind it with a reference and it tracks the progress of the element from 0 to 1.

Notice how we also transformed the Heading at the top of the page. This was possible because of useTransform.

We essentially took scroll progress and converted it to a value we want to use to translate the header to the top, creating a parallax effect.

const translate = useTransform(scrollYProgress, [0, 1], [0, -100]);

This means when the scroll position goes from 0 → 1, change the translate from 0 → 100.

Try it yourself

Here's a quiz for you. Try using useTransform to fill up the progress bar on the top of the page.

There are real use cases for hooks. For example, if you want to translate a navbar when the user scrolls, you want hooks like useMotionValueEvent to watch for scroll changes. Based on the progress, you can watch for changes and translate the navbar accordingly.

Based on the scroll progress, we are flipping a switch to move the navbar up and down. The flip logic lives inside the useMotionValueEvent hook.

Comet Card

Another hook that is useful is useMotionTemplate. This hook is primarily used to interpolate motion values.

For example, the code snippet won't work

const blur = useMotionValue(10);
 
<motion.div style={{ filter: `blur(${blur}px)` }} />

For a motion value to resolve into something that you want to programmatically change, you need to use useMotionTemplate.

Here's an example of Comet Card that I built at Aceternity UI. It's a simple card that rotates and translates based on the mouse position. Also it has a glare that moves.

  1. It uses a lot of hooks, so sorry about that.
  2. The glare actually uses a radial gradient. The X and Y values are used to position the gradient. We are moving them with mouse pointer, hence the glare moves.

Hooks can be pretty useful if used with the right intent. Combine useSpring with your existing hooks like useTransform to animate any property you like.