React Modal too many re-renders; React setState too many re-renders; This issue was encountered when I was handling the React Modal open and close handlers from parent to the child function component. The react-model component I was using.
Problem Code
import React from 'react';
import './style.css';
import MyModalComponent from './mymodal.component';
export default function App() {
const [modalIsOpen, setIsOpen] = React.useState(false);
function handleCloseModal(event) {
console.log(event);
}
return (
<div>
<h1>Hello StackBlitz!</h1>
<p>Start editing to see some magic happen :)</p>
<MyModalComponent
IsModalOpened={modalIsOpen}
onCloseModal={() => handleCloseModal}
/>
<button onClick={setIsOpen(true)}>Open Modal</button>
</div>
);
}
I faced the following issue:
Too many re-renders. React limits the number of renders to prevent an infinite loop.
The code in mymodal.component.js
Solution
If you look closely at
<button onClick={setIsOpen(true)}>Open Modal</button>
The functional components useState we use to handle a state, here we have called the setIsOpen() method directly. Which is getting called soon after the component mount stage, and keeps on rerender the state and getting stuck into loops.
We need to replace the code above with this:
<button onClick={() => setIsOpen(true)}>Open Modal</button>
Now the setIsOpen() will be triggered on click only.
Check the complete tutorial for React Modal using react-modal and open modal from the parent function component.
Hence resolved 🙂
Leave a Reply