search

Home  >  Q&A  >  body text

React warning: Update depth exceeded maximum limit when updating state in useEffect

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>
)
P粉447785031P粉447785031498 days ago582

reply all(1)I'll reply

  • P粉163465905

    P粉1634659052023-09-07 00:06:51

    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 .

    useEffect(() => {
        if (data && data.length > 0 ) {
          setModalState({
            ...modalState,
            showModal: true,
            showNoUsersModal: false,
          });
        } else if (data && data.length == 0) {
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: true,
          });
        }
      },[]);

    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.

    useEffect(() => {
        if (data && data.length > 0 ) {
          setModalState({
            ...modalState,
            showModal: true,
            showNoUsersModal: false,
          });
        } else if (data && data.length == 0) {
          setModalState({
            ...modalState,
            showModal: false,
            showNoUsersModal: true,
          });
        }
      },[]);

    reply
    0
  • Cancelreply