22
loading...
This website collects cookies to deliver better user experience
Uncaught Error: Too many re-renders.
React limits the number of renders
to prevent an infinite loop.
function App() {
const [count, setCount] = useState(0);
setCount(1); // infinite loop
return ...
}
useEffect
with an empty array as a dependency.function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(1);
}, [])
return ...
}
function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(count + 1) // infinite loop
}, [count])
return ...
}
useEffect
with a property you update set as a dependency, it will cause an infinite loop.count
updates → useEffect
detects updated dependency → count
updates → useEffect
detects updated dependency → ...function App() {
const [count, setCount] = useState(0);
useEffect(() => {
setCount(previousCount => previousCount + 1)
}, [])
return ...
}
export default function App() {
const [count, setCount] = useState(0);
return (
<button onClick={setCount(1)}>Submit</button> // infinite loop
);
}
onClick
, not the result of the function execution. By executing a function before setting a handler, you update a state inside the render, which causes an infinite loop.onClick
event. It is a proper way to set event handlers. This way state will only update after a click of a button and won't cause an infinite loop.export default function App() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(1)}>Submit</button> // infinite loop
);
}