I'm trying to update my state variable which is an object containing a boolean variable. Once the data is available (in response to an API call invoked on button click), I update my state inside useEffect. Then with this data I call another component, a modal, and if no data is available, I show another modal. When I close the popup, the state variable should be updated.
const [modalState, setModalState] = useState<IModalState>({ showNoUsersModal: false, showModal: false, }); useEffect(() => { if (data && data.length > 0) { setModalState({ ...modalState, showModal: true, showNoUsersModal: false, }); } else if (data && data.length === 0) { setModalState({ ...modalState, showModal: false, showNoUsersModal: true, }); } }); const onApplicationSuccess = () => { setModalState({ ...modalState, showModal: false, showNoUsersModal: false, }); } const onClose = () => { setModalState({ ...modalState, showModal: false, showNoUsersModal: false, }); } return ( <div> {modalState.showNoUsersModal && ( <NoUsersFoundModal onCancel={() => setModalState({ ...modalState, showModal: false, showNoUsersModal: false, }) } /> )} {modalState.showModal && ( <SomeOtherModal onCancel={() => setModalState({ ...modalState, showModal: false, showNoUsersModal: false, }) } /> )} </div> )
This issue was because you didn't pass any dependency array to useEffect so when ever state was changing useEffect was calling again. here is the solution .
The problem is because you don't pass any dependency array to useEffect, so useEffect will be called again every time the state changes. Here is the solution.