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)}>
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}>
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)}>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With