'Nextjs shallow routing for tabs?

Have a tabs component which work perfectly with the router.query state

useEffect(() => {
        let found = false;

        if (currentTab !== 'leads') {
            router.push(`${id}?tab=${currentTab}`, undefined, {
                shallow: true,
            });
        }
    }, [currentTab]);

    useEffect(() => {
        if (router.query.tab !== currentTab) {
            setCurrentTab(router.query.tab);
        }
    }, [router.query.tab]);

The problem arises when the rendered tab component push its own query state.

useEffect(() => {
        router.push(`?${queryString.stringify({tab:"y")}`, undefined, {
            shallow: true,
        });


    }, [state]);

the below useEffect router.push tab doesnt affect the second useEffect. so if i move tab from x to y. the url bar tab stucks to x but the component works fine.



Solution 1:[1]

Can you make a reproduction in code sandbox? I use query params in tabs, but different approach.

I use this custom hook (with MUI tabs). It returns a tab value and onChange which I pass to tabs.

export const useTabsValue = (): [TabsValue, TabsOnChange] => {
  const router = useRouter();

  const currentTab = router.query[QUERY_PARAM__PROFILE_TAB] ?? 0;

  return [
    Number(currentTab),
    (event: React.SyntheticEvent, newValue: number) => {
      if (newValue === 0) {
        router.push('/profile');
        return;
      }

      router.push(`/profile?${QUERY_PARAM__PROFILE_TAB}=${newValue}`);
    },
  ];
};

Usage

const [value, onChange] = useTabsValue();

This would require you to change how your tabs work. But most of the tabs should get onChange handler (maybe check radix-ui for accessible tabs)

You can also check out next-query-params lib that may help you out, for controlling the query params state.

Hope something helps you from this. Best, Hypercloud

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 hypercloud