How to Prevent Multiple Button Clicks in React?

Estimated read time 1 min read

Preventing multiple button clicks in React is important to avoid multiple actions being triggered and ensure that the user’s action is performed only once. Here’s an example of how to prevent multiple button clicks using a state variable:

import React, { useState } from 'react';

function MyButton() {
  const [isLoading, setIsLoading] = useState(false);

  const handleClick = () => {
    if (!isLoading) {
      // Perform the action here

  return (
    <button onClick={handleClick}>
      {isLoading ? 'Loading...' : 'Click Me'}

export default MyButton;

In the code above, we define a state variable isLoading and an event handler handleClick that performs the action when the button is clicked, but only if isLoading is false. When the button is clicked, isLoading is set to true, preventing further clicks until the action is completed.

In the button’s JSX, we conditionally render the button label based on the value of isLoading. If isLoading is true, we display a loading message, otherwise, we display the regular label.

This approach prevents multiple button clicks by disabling the button after the first click until the action is completed, ensuring that the user’s action is performed only once.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply