skip to Main Content

Warning: Maximum update depth exceeded. This can happen when a component calls setState inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on every render.

 const OwnerPage = () => {
  const onOpen = useAgencyModal((state) => state.onOpen);
  const isOpen = useAgencyModal((state) => state.isOpen);
  const params = useParams();
  const [owner, setOwner] = useState<User | null>(null);
  const [agency, setAgency] = useState<any>([]);
  useEffect(() => {
    const fetchData = async () => {
      try {
        const response = await fetch(`/api/owner/${params.ownerId}`, {
          method: "GET",
        });
        const data = await response.json();
        setAgency(data.agency);
        setOwner(data.owner);
        console.log("agency: " + data.agency);
        console.log("owner: " + data.owner);
      } catch (error) {
        console.error("Error occurred while fetching data:", error);
      }
    };
    fetchData();
  }, [params.ownerId]);
  const memoizedData = useMemo(() => {
    return { agency, owner };
  }, [agency, owner]);
  useEffect(() => {
    if (memoizedData.agency !== null) {
      if (!isOpen) {
        onOpen();
      }
    } else {
      redirect(`/dashboard/owner/${params.ownerId}/dashboard`);
    }
  }, [memoizedData.agency, isOpen, onOpen, params.ownerId]);
  return null;
};

2

Answers


  1. (I want to comment but my reputation is less than 50,,)

    I’m quite new to react but I’ve seen that warning several times. And it’s mostly because of infinite loop of useEffect for wrong dependencies.

    I think the second useEffect causes the infinite loop. If memoizedData.agency is not null and isOpen is false, trigger onOpen. Then this causes state changes, re render, if memoizedData.agency, isOpen still meets the condition, re trigger onOpen, re render, …

    Maybe it helps you to find the real problem.🧐

    Login or Signup to reply.
  2. There is some context missing of what useAgencyModal is doing. Many lines in this code is also redundant.

    1. useMemo is used for saving calculated values to prevent recalculation after every rendering cycle. Since all memorized values are already available without any additional operation you can remove those lines.
      const memoizedData = useMemo(() => {
        return { agency, owner };
      }, [agency, owner]);
    
    1. States of useState with the same dependency in the useEffect dependency array often leads of a circular dependency which leads to this Warning. It helps to check where the state update triggers a useEffect which will trigger another state update.
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search