isPublished: true title: Tracking Scroll Progress and Direction with Motion for React description: Do you need to track scroll progress and direction for your scroll-linked animations? We'll look at how to easily accomplish this using Motion for React. date: '2024-12-16' categories:

  • react
  • motion for react
  • framer motion

Tracking Scroll Progress and Direction with Motion for React

0%
Scroll direction is down
Scroll progress: 0%

The building blocks of complex scroll-driven animations are actually pretty simple to set up using Motion for React. We can track page scroll and scroll direction in just a few lines of code.

Scroll Progress

const { scrollYProgress } = useScroll()

scrollYProgress is an automatically tracked motion value between 0 and 1. It approaches 1 as we scroll toward the bottom of the page.

Scroll Direction

To track scroll direction, we just need to take the difference between the current and previous scrollYProgress.

We'll use React state to keep track of the current direction as well as the latest scrollYProgress value – this will become the previous scroll in the context of executing our event handler when scroll changes.

We can use Motion's useMotionValueEvent to update our state any time scrollYProgress changes. We'll pass in the current motion value as an argument to our handler. Then we'll subtract the lastScrollY.

The resulting diff tells us the current scroll direction. We've used 1 and -1 to represent scrolling down and up, respectively.

const [[direction, lastScrollY], setDirection] = useState([1, 0])
 
useMotionValueEvent(scrollYProgress, 'change', (currentScrollY) => {
  setDirection([currentScrollY - lastScrollY > 0 ? 1 : -1, currentScrollY])
})

Okay, we're finished

Happy Animating

The interactive component showing in this post was built off the code shared above. What scroll-linked animations will you build?

Motion also provides some great examples for inspiration.

Thanks for reading!