Reputation: 127
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)}>
Upvotes: 3
Views: 1437
Reputation: 21
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.
Upvotes: 2
Reputation: 1280
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)}>
Upvotes: 3
Reputation: 943630
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}>
Upvotes: 3