skip to Main Content

I want to store the previousValue of scrollYProgress of framer motion. I want to render something depending on the difference between previous and latest value. How to get and store it?

useMotionValueEvent(scrollYProgress, "change", (latest) => {
    console.log(scrollYProgress.get());
});

2

Answers


  1. Chosen as BEST ANSWER

    I did it with my own. It was the solution:

    const [prevValue, setPrevValue] = useState(0);
    useMotionValueEvent(scrollYProgress, "change", (latest) => {
        console.log("Current value:",scrollYProgress.get()); // Log the 
    numeric value
        setPrevValue(latest);
        console.log("Previous value:", prevValue);
    });
    

  2. To achieve this in Framer Motion, you can use React’s useState hook to store the previous and latest values of scrollYProgress. Here’s an example of how you can modify your code:

    import { useState } from 'react';
    import { useMotionValueEvent } from 'framer-motion';
    
    // Your component
    const YourComponent = () => {
      const [previousScrollYProgress, setPreviousScrollYProgress] = useState(0);
    
      // Assuming scrollYProgress is defined somewhere in your component
      useMotionValueEvent(scrollYProgress, 'change', (latest) => {
        const previous = previousScrollYProgress;
        const difference = latest - previous;
    
        // Render something based on the difference
        if (difference > 0) {
          // Do something when scrolling down
        } else if (difference < 0) {
          // Do something when scrolling up
        }
    
        // Store the latest value for the next iteration
        setPreviousScrollYProgress(latest);
      });
    
      return (
        // Your component JSX
      );
    };
    
    export default YourComponent;

    In this example, previousScrollYProgress is a state variable that holds the previous value of scrollYProgress. Whenever the scrollYProgress changes, it calculates the difference between the previous and latest values and then updates the state with the latest value for the next iteration. This way, you have access to both the previous and latest values in the event handler.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search