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?