iTranslated by AI
The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
😗
Implementing Double-Click Prevention in React
React: Implementing Prevention of Multiple Clicks
What are Multiple Clicks?
In a standard form button implementation, if the button is clicked multiple times within the processing timeframe, the process will execute that many times. For example, if you click "Purchase" on an e-commerce site like Amazon, and "multiple click prevention" is not properly implemented, a double-click would cause the process to run twice. This leads to the risk of duplicate purchases and unnecessary charges. The "Implementation for Multiple Click Prevention" discussed here is designed to prevent such occurrences.
Key Points for Multiple Click Prevention
Use useRef to manage the flag for whether a process is currently running. This ensures that changing the value does not trigger a re-render.
const SubmitForm = () => {
const processing = useRef(false)
const handleSubmit = (e) => {
e.preventDefault()
e.stopPropagation()
// Return if already processing
processing.current && return
processing.current = true
setTimeout(() => {
// Set processing back to false after 3000ms
process.current = false
}, 3000)
}
return (
<form onSubmit={handleSubmit}>
<button type="submit">Submit</button>
</form>
)
}
- processing: A flag representing whether a process is currently running.
-
e.preventDefault: Cancels the default browser behavior of "page reloading" upon submission. -
e.stopPropagation: Cancels the propagation of the event. - If the current state of processing (
processing.current) is true (currently processing), the function exits without performing the asynchronous task. -
setTimeoutis used to set the processing state back to false after 3000ms, representing the asynchronous task duration.
Reference
- What is the optimal solution for preventing multiple clicks in React apps?
- Preventing click events on double-clicks using React, a high-performance method
- [React] A HOC that provides functionality to prevent duplicate processes from double-clicks
- Understand the differences between return false;, preventDefault();, and stopPropagation() in 1 minute
Discussion