score:2
Accepted answer
you should wrap that callback task into a reducer and trigger the timeout as an effect. yes, that makes things certainly more complicated (but it's "best practice"):
const button = ({ clickhandler, clickholdhandler, children }) => {
const holdtime = 1000;
const [holding, pointer] = usereducer((state, action) => {
if(action === "down")
return { holding: true, time: date.now() };
if(action === "up") {
if(!state.holding)
return { holding: false };
if(state.time + holdtime > date.now()) {
clickhandler();
} else {
clickholdhandler();
}
return { holding: false };
}
if(action === "leave")
return { holding: false };
}, { holding: false, time: 0 });
useeffect(() => {
if(holding.holding) {
const timer = settimeout(() => pointer("up"), holdtime - date.now() + holding.time);
return () => cleartimeout(timer);
}
}, [holding]);
return (
<button
onmousedown={() => pointer("down")}
onmouseup={() => pointer("up")}
onmouseleave={() => pointer("leave")}
>
{children}
</button>
);
};
working sandbox: https://codesandbox.io/s/7yn9xmx15j
as a fallback if the reducer gets too complicated, you could memoize an object of settings (not best practice):
const state = usememo({
isholding: false,
holdstarttime: undefined,
}, []);
// somewhere
state.isholding = true;
Source: stackoverflow.com
Related Query
- Function called in setTimeout not using current React state
- React DnD useDrop is not using the current state when the method is called
- React - useState - why setTimeout function does not have latest state value?
- Axios not updating state from API in function called on Click, but works on identical function on Component Mount in React
- React Hooks state not working properly when the function calling it is called in another function
- The state variable returned after using useState react hook shows .map is not a function
- react function not using updated state
- Mock function not being called using jest and testing library on react app
- Why does the setTimeOut not being cleared by using clean up function in React (useEffect)?
- React function not setting state after being called in constructor
- Set State not getting called in parent function in React
- React - member function is not a function when called in initial state (outside constructor)
- React Hooks state variable not updated during setTimeout function
- State is not getting updated in Function Component using useState in React
- React state not correct when function called via addEventListener
- React state not updating using immutability helper update function
- React - State is defined in one parent function, but not in the other parent function being called from the child
- State not updating when using React state hook within setInterval
- TypeError dispatcher.useState is not a function when using React Hooks
- React shouldComponentUpdate() is called even when props or state for that component did not change
- Uncaught TypeError: create is not a function using useEffect React Hook with AJAX request
- UI not re-rendering on state update using React Hooks and form submission
- Using JS React component in TypeScript: JSX element type 'MyComponent' is not a constructor function for JSX elements
- State using React Typescript: Property does not exist on type 'IntrinsicAttributes & IntrinsicClassAttributes
- React onLoad event on image tag is not getting called when using conditional render
- React hooks state not using latest
- Unsafe legacy lifecycles will not be called for components using new component APIs. React v16.3
- React: How to add onChange functionality inside of Function component using React Hooks? Need onClick event from a checkbox to influence input state
- React Using useState/Hooks In HOC Causes Error "Hooks can only be called inside of the body of a function component"
- React - State Hook map is not a function
More Query from same tag
- How do I use Firebase and react to create static information that all my users have access to?
- How to check Api is triggered or not and how to abort the api if its triggered
- Material Ui button colors not changed after theme change
- Correct way to calculate download percentage with node-fetch
- How to wrap elements populated by array of objects in pairs
- Stateless component with nested component property
- React Materialize CSS full-screen height
- React Router: Route with nested params not hit
- state field undefined upon using local storage to persist state
- Browser forward button not active with React.js
- React doesn't render array value from firebase and array's length is 0 despite having the value on console
- React router not getting refreshed after routing
- How to switch className between different buttons
- Can't get my component to conditionally render out
- When the form is empty, pressing the Login button opens the page. I have to make a mistake
- How to get user info with a valid Bearer Token?
- how to submit a formik form through mutation with ApolloClient?
- React.createElement: type is invalid -- expected a string
- Error: Objects are not valid as a React child (found: [object Promise])
- React component triggering alert before button press along with a POST request before user input
- Loading a ,js Script in React, issues on Pagination/NavBar Links
- React JS & Axios Render after getting response data
- AWS Amplify Google auth user not redirected back
- get array of object's first two keys as keys in new object and third key as array in that object
- How to handle React Router Recursive Paths?
- How to make next/image fill available grid space?
- React - how to show the difference between the current and next props?
- Array not getting cleared to null or empty in setState on click in react
- Render a react.js component with document.write() inside
- NW Js throwing net::ERR_UNKNOWN_URL_SCHEME when accessing files on hd