Can you please explain why the following results in an infinite loop with the following error:
Uncaught Invariant Violation: Too many re-renders. React limits the number of renders to prevent an infinite loop.
import React from "react";
import { useState } from 'react';
function MyImageComponent(props) {
const {
images
} = props;
const [windowWidth, updateWindowDimensions] = useState(window.innerWidth);
window.addEventListener('resize', updateWindowDimensions(window.innerWidth)); //error here
return (
<div>
{windowWidth}
</div>
);
}
export default MyImageComponent;
I believe I can solve using the useEffect
API but I don't understand conceptually what the problem is... it appears the render is being called multiple times because state is being set in a loop... but given the update function updateWindowDimensions
is binded to an event listener which is not running infinitely I don't understand it.
To note: the error appears with or without a window resize.
window.addEventListener('resize', () => updateWindowDimensions(window.innerWidth))