Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

"Too many re-renders. React limits the number of renders to prevent an infinite loop" error when useState hook is used

import {useState} from 'react';

const Counter = () =>{

    let [counter,setCounter] = useState(0);

    return(
       <div className='counter-box'>
            <span>{counter}</span>
            <button onClick={setCounter(counter++)}></button>
       </div>
    )
}
export default Counter;

I’m using functional component here. Can someone tell me what’s wrong with my code?

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Yes.
Here the onClick function is getting executed when it’s rendered instead of user click event.

Solution 1:

import {useState} from 'react';

const Counter = () =>{

    let [counter,setCounter] = useState(0);

    return(
       <div className='counter-box'>
            <span>{counter}</span>
            <button onClick={e => setCounter(counter+1)}></button>
       </div>
    )
}
export default Counter;

Instead of executing the code, we pass a function reference(anonymous arrow function) to the onClick event.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading