0

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.

2 Answers 2

3

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 … ∞

Sign up to request clarification or add additional context in comments.

3 Comments

Is there a way to insert a code block directly in the template without it being wrapped in a function like OP wanted ? (I don't know much of react)
@Seblor — You have to create the function at some point. You could do it outside the JSX part and store it in a variable.
I see. I'm used to work with VueJS where there can be either a function or a statement directly in the template. Thanks for answering :)
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.