Capítulo 46 de 142

Chapter 46: useScroll

Core Idea

Create scroll-linked animations like progress bars & parallax with the useScroll React hook.

Key Concepts

  • Page scroll: By default
  • Element scroll: To track the scroll position of a scrollable element we can pass the element's ref to useS
  • Element position: We can track the progress of an element as it moves within a container by passing its ref
  • Scroll offsets: With the offset option we can define which parts of the element we want to track with the viewport
  • Performance: Browsers are capable of animating some values
  • Find & fix animation performance issues with your agent.: MotionScore for Agents grades animations in your source code S to F and hands your agent s
  • container: Default: Viewport
  • target: useScroll tracks the progress of the target within the container.
  • axis: Default: "y"

Code Examples

const { scrollYProgress } = useScroll()

return <motion.div style={{ scaleX: scrollYProgress }} />
  • What it demonstrates: Core usage pattern for useScroll.

Anti-patterns

  • Note from docs: Since scrollY is a MotionValue, there's a neat trick you can use to tell when the user's scroll direction changes:
  • Note from docs: ```
  • Note from docs: const { scrollY } = useScroll()
  • Note from docs: const [scrollDirection, setScrollDirection] = useState("down")

Key Takeaways

  1. scrollX/Y: The absolute scroll position, in pixels.
  2. scrollXProgress/YProgress: The scroll position between the defined offsets, as a value.
  3. useScroll supports Page scroll.

Connects To

  • Motion Values: related Motion doc page.
  • React scroll animation: related Motion doc page.
  • React Animation: related Motion doc page.
  • Parallax example & tutorial for React: related Motion doc page.