Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

exhaustive-deps infinite loop with function dependant on component state

Given the following example

const SettingsLayout = () => {
  const [tabs, setTabs] = useState(SettingsNavigation);
  const router = useRouter();

  const updateActiveTab = useCallback(
    (pathname) => {
      setTabs(
        tabs.map((tab: Tab) => ({
          ...tab,
          current: tab.href === pathname,
        }))
      );
    },
    [tabs]
  );

  useEffect(() => {
    updateActiveTab(router.pathname);
  }, [router.pathname]);
  // exhaustive-deps wants me to add updateActiveTab to the dependency array
  // but adding it will cause an infinite render loop
  // Flux:
  //   -> useEffect will change tabs
  //   -> tabs will change updateActiveTab
  //   -> updateActiveTab will execute useEffect

  return (...)
}

So far i have not found a solution other than disabling exhaustive-deps, i’ve read you shouldn’t do it.

How can i execute updateActiveTab only when router.pathname changes?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Check this out!

const SettingsLayout = () => {
  const allTabs = SettingsNavigation;
  const [tabs, setTabs] = useState();
  const router = useRouter();

  const updateActiveTab = useCallback(
    (pathname) => {
      setTabs(
        allTabs.map((tab: Tab) => ({
          ...tab,
          current: tab.href === pathname,
        }))
      );
    },
    [allTabs]
  );

  useEffect(() => {
    updateActiveTab(router.pathname);
  }, [router.pathname]);

  return (...)
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading