Reputation: 11
When I use setMiddle(true) it getting an error "Too many re-renders.."
Can you please tell me why?
import React, { useState } from "react";
const App = () => {
const [ test, setTest ] = useState(true)
const [ test1, setTest1 ] = useState(false)
const [ middle, setMiddle ] = useState(false)
const setFrame = () => {
console.log('123')
setTest1(false)
}
const titleScreen = () => {
setMiddle(true)
setFrame('myRoom');
return
}
const renderFrame = () => {
return (<div>Ta-daa!</div>)
}
return (
<div>
{test1 ? renderFrame() : null}
{test ? titleScreen() : null}
</div>
)
}
export default App
But when I deleting the line setMiddle(true) and setTest1(false) it works
Upvotes: 1
Views: 112
Reputation: 2245
This happens because test
is true at the beginning, so titleScreen()
is called, and inside that function, you mutate the state which fires a re-render, and since test
never changes its value, it calls again titleScreen()
and then you fall in the phantom zone called The Infinite Loop. 👻
How you prevent it? always mutate the state when something happens in your application, a user interaction, an API call, etc. never do it on page render, or if you do it, make sure you break the condition, in this case change test
value at some point.
Upvotes: 1