2

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

<button className="btn-primary" onClick={setSamplePageData(1)}>
Mark Lakata
  • 19,989
  • 5
  • 106
  • 123
Arunkumar09
  • 117
  • 1
  • 8
  • 1
    I can't reproduce the issue. https://codesandbox.io/s/so-hyji1k?file=/src/App.js – Quentin Apr 12 '22 at 10:04
  • 1
    `onClick={() => setSamplePageData(1)}` – 0stone0 Apr 12 '22 at 10:10
  • 1
    Does this answer your question? ["Error: Too many re-renders. React limits the number of renders to prevent an infinite loop."](https://stackoverflow.com/questions/59304283/error-too-many-re-renders-react-limits-the-number-of-renders-to-prevent-an-in) – 0stone0 Apr 12 '22 at 10:12

3 Answers3

3

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}>
 
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
3

It's because setSamplePageData is instantly called upon render and when you set state you trigger render event thus creating infinite loop.

Instead define a inline function in onClick event

<button className="btn-primary" onClick={() => setSamplePageData(1)}>
Emil
  • 1,186
  • 1
  • 8
  • 17
2

Because if you don't use the parenthesis react call function on every render and it will cause so many re-renders you should change your onClick event handler to this

onClick={() => setSamplePageData(params)}

these parentheses in onClick prevents the function from being called on every render.

sunay
  • 21
  • 1