Sudhanva BS
Sudhanva BS

Reputation: 15

Why should the function which is called for 'onClick' here in this code snippet bellow should be called inside another arrow function?

Here is the code snippet...

const CountClicks = () => {
    const [count, setCount] = useState(0);
    return(
        <div>
            <p>You clicked {count} times.</p>        
            <button onClick={() => {setCount(count + 1)}}>
                Click me
            </button>
        </div>
    );
}

I tried <button onClick={setCount(count + 1)}> which led to the following errors being displayed:

Uncaught Error: Too many re-renders. React limits the number of renders to prevent an infinite loop.

Upvotes: 0

Views: 184

Answers (2)

Ahsan-J
Ahsan-J

Reputation: 346

What onClick expects is a function. Using Anonymous Closure fat arrow function (() => {setCount(count + 1)}) you are passing a function as prop. even passing function as prop like onClick={setCount} you are passing a function. But if you use onClick={setCount(count + 1)}, what you actually are doing is passing the return value of setCount function on every render. onClick is event handler that expects a function.

Upvotes: 0

Quentin
Quentin

Reputation: 943510

The value assigned to onClick must be a function.

onClick={setCount(count + 1)} will call setCount immediately and assign its return value as the function to call when the element is clicked.

Since it doesn't return a function, nothing would happen if it was clicked.

However, it never gets that far because calling setCount changes the state and triggers a rerender … which calls setCount and triggers a rerender which … ∞

Upvotes: 3

Related Questions