reactjs / react.dev

The React documentation website
https://react.dev/
Creative Commons Attribution 4.0 International
10.98k stars 7.51k forks source link

Question: Unable to access the updated state in requestAnimationFrame's call back function. #4868

Closed ayushbisht2001 closed 2 years ago

ayushbisht2001 commented 2 years ago

Hey, team React! can you please help me?

I'm currently working on a project in which I am trying to animate a box, based on the virtual-scroll deltaY parameters. But the problem is that the state which holds the deltaY parameters doesn't reflect the changes when accessing the value at the callback function. I'm using requestAnimationFrame for throttling the scroll events and animating the box with gsap's Tweenlite.

Any workaround for doing this stuff, is also helpful, Thanks.

  function handleScroll(event){

    let targetModifier = event.deltaY

    SetTargetPos( (prev) => ( { 
      ...prev,
      targetPosY : prev.targetPosY + targetModifier,
      oldDeltaY : event.deltaY 
    }))

    debounceBackToSlide()

  }

 function wheelLoop(time){

    let newSlideTransformTemp = target_pos.slideTransform + (target_pos.targetPosY - target_pos.slideTransform) * .09

    newSlideTransformTemp =  getRoundedValue(newSlideTransformTemp)

    setNewSlideTransform( () => newSlideTransformTemp)

    animateFrame.current = requestAnimationFrame(wheelLoop)

  }

  useEffect(() => {

    const slideLimit = 165
    console.log("gsap update")

    gsap.to(ref.current, {y: target_pos.slideTransform, force3D: true})

    if(target_pos.slideTransform <= -slideLimit ){
      nextSlide()
      _.delay(resetWheel,500)

    }
    else if (target_pos.slideTransform >= slideLimit){
      prevSlide()
      _.delay(resetWheel,500)

    }
    else{

      animateFrame.current = requestAnimationFrame(wheelLoop)

    }

  }, [newSlideTransform])

  useEffect(() => {

    let vs = new VirtualScroll({
      el: ref.current,
      mouseMultiplier: 0.4,
      keyStep: 400,
    });

    vs.on(handleScroll);

    wheelLoop()

    return () => {
      vs.destroy();
    };

  }, []);
eps1lon commented 2 years ago

Support requests filed as GitHub issues often go unanswered. We want you to find the answer you're looking for, so we suggest the following alternatives:

Coding Questions If you have a coding question related to React and React DOM, it might be better suited for Stack Overflow. It's a great place to browse through frequent questions about using React, as well as ask for help with specific questions.

https://stackoverflow.com/questions/tagged/react

Talk to other React developers There are many online forums which are a great place for discussion about best practices and application architecture as well as the future of React.

https://reactjs.org/community/support.html

ayushbisht2001 commented 2 years ago

Thanks, @eps1lon