Using PanResponder in Functional Components: why useRef on panResponder variable?
Asked Answered
B

1

6

In the React Native docs on PanResponder , their functional component example applies a useRef to the PanResponder variable they create.

const panResponder = useRef(
  PanResponder.create({
    onMoveShouldSetPanResponder: () => true,
    onPanResponderGrant: () => {
      pan.setOffset({
        x: pan.x._value,
        y: pan.y._value
      });
    },
    onPanResponderMove: Animated.event(
      [
        null,
        { dx: pan.x, dy: pan.y }
      ]
    ),
    onPanResponderRelease: () => {
      pan.flattenOffset();
    }
  })
  ).current

If we remove useRef here, the component still works as expected. So why did they choose to include useRef?

My guess is that it prevents the panResponder variable from being repeatedly destroyed and created, providing some efficiency gains. Is this the true, and is this the only benefit?

I've attempted to use this same pattern in one of my programs, but have noticed an issue where one of the methods of the PanResponder does not reflect the status of an updated prop (enabled). The following code is inoperative, as the onStartShouldSetPanResponder appears to initialize with enabled=false, and persist despite the enabled prop updating to true.

const panResponder = useRef(
  PanResponder.create({
    // we want this component to become the responder when the enabled prop is true
    onStartShouldSetPanResponder: () => enabled,

In this case, should I still be using useRef? Or would a better thing to use be React.memo to prevent unnecessary rerenders while still allowing me to update my PanResponder with the enabled prop?

Barbaric answered 22/6, 2020 at 14:10 Comment(0)
A
0

Basically, even I am not sure about this properly but as per my understanding, Refs help you to catch the current value of the movement instance on the DOM node as the functional component doesn't have an instance and it doesn't allow you to use React.Component and ref help more in keeping the track of the about your view, text etc to get animation's current value and PanResponder would keep animation in flow with touches from the user and manipulation of value on that basis....

Artificiality answered 29/9, 2022 at 7:39 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.