Reputation: 445
I'm implementing a solution in a React Native to avoid double taps on React Native Router Flux and I came up with this custom hook. What I really don't know is if this is a valid use case for this. Basically I created this as a hook because I'm using the useRef hook inside it. But maybe just a helper function would've been enough.
I also have a wrapper component for Pressable
and a HOC for other components that may require onPress
, this is for the current case where my press function call is neither of both.
Hook:
import { useRef } from 'react';
import { Platform } from 'react-native';
const timeout = Platform.OS === 'android' ? 2000 : 1000;
const useSafePress = () => {
const disabled = useRef(false);
const onSafePress = fn => {
if (!disabled.current) {
fn();
disabled.current = true;
setTimeout(() => {
disabled.current = false;
}, timeout);
}
};
return onSafePress;
};
export default useSafePress;
Usage:
const MyComponent = () => {
const onSafePress = useSafePress();
[...]
return (
<SomeOtherComponent
open={isOpen}
icon={isOpen ? 'window-close' : 'plus'}
actions={[
{
icon: 'share',
label: 'Action 1',
onPress: () => onSafePress(onPressShare),
},
{
icon: 'calendar-month',
label: 'Action 2',
onPress: () => onSafePress(onPressCalendar),
},
]}
color={white}
onStateChange={onStateChange}
/>
);
};
Upvotes: 0
Views: 109
Reputation: 611
This varies on opinion for sure. In my opinion, you are just wrapping a singular function and maybe it doesn't have enough unique logic to warrant it being a hook.
Either way, this works, and it's really just a stylistic choice. In my projects, I try to only extract hooks when I find myself using a collection of hooks/logic over and over again in multiple places. Or there's lots of common logic that utilize a specific hook.
Upvotes: 1