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.
  • setTimeout is used to set the processing state back to false after 3000ms, representing the asynchronous task duration.

Reference

GitHubで編集を提案

Discussion