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

Why react throws error, if we try to change state on a On Click function itself

I am learning react hooks for last few days, but i cannot figure it out why I am getting this error.

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

use state variables

 const [count, setSamplePageData] = useState(0);

changing state in onclick

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

<button className="btn-primary" onClick={setSamplePageData(1)}>

>Solution :

You’re calling setSamplePageData and passing it the argument 1 during the render step. (Which triggers a new render, which calls the function again, ad infinitum).

Then you’re passing the return value of that (which is, IIRC, undefined) to onClick.

You need to pass a function to onClick.

 const [count, setSamplePageData] = useState(0);
 const clickHandler = () => setSamplePageData(1);
 // ...
 <button className="btn-primary" onClick={clickHandler}>
 
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