[NextJS] 13버전에서 useRouter훅을 사용하려는데 ‘NextRouter was not mounted.’ 에러가 난다

선영·2023년 7월 20일
0

📚 Library

목록 보기
10/14
post-thumbnail

🧨 문제


아래와 같이 gnbMenu컴포넌트에서 useRouter훅을 임포트해서 사용하려고 했다. 12버전에서는 문제없이 작동했지만, 13버전에서는 에러와 함께 작동하지 않았다.

// before
import {useRouter} from 'next/router'

export default function Header() {
	const router = useRouter()

    const gnbMenu = (menu) => {
        return (
            <li
                key={menu.gnb_menu_no}
                className={
                    menu.gnb_menu_bold == 1
                        ? 'live'
						// 이 부분에서 에러가 난다.
                        : router.asPath === '/m/brands' && menu.gnb_menu_name === '브랜드'
                        ? 'current'
                        : ''
                }
            >
            </li>
        )
    }

    return (
        <>
          {globalGnb.map((item) => {
              return gnbMenu(item)
          })}
        </>
    )
}

🤔 원인 및 해결


공식문서에 따르면 13버전이 되면서 useRouter훅이 리턴하는 asPath프로퍼티가 삭제되었나보다.

===quoted===

In addition, the new useRouter hook has the following changes:

  • isFallback has been removed because fallback has been replaced.
  • The localelocalesdefaultLocalesdomainLocales values have been removed because built-in i18n Next.js features are no longer necessary in the app directory. Learn more about i18n.
  • basePath has been removed. The alternative will not be part of useRouter. It has not yet been implemented.
  • asPath has been removed because the concept of as has been removed from the new router.
  • isReady has been removed because it is no longer necessary. During static rendering, any component that uses the [useSearchParams()](https://nextjs.org/docs/app/api-reference/functions/use-params) hook will skip the prerendering step and instead be rendered on the client at runtime.

===end===

그래서 공식문서를 참고해서 useRouter훅 대신 usePathname훅을 사용하였고, 아래와 같이 코드를 업데이트 해주었다.

// after
'use client';

import {usePathname} from 'next/navigation';

export default function gnbMenu() {
		const pathname = usePathname();
    const [currPath, setCurrPath] = useState('');

    useEffect(() => {
        // 브랜드메뉴 페이지가 렌더링되면 url의 path를 구한다 (예를들면 /brands)
        setCurrPath(pathname);
    }, [pathname]);

    return (
        ...생략
              {gnbMenu.length !== 0 &&
                  gnbMenu.map((menu: MenuProp) => (
                      <li
                          key={menu.gnb_menu_no}
                          className={
                              menu.gnb_menu_bold == 1
                                  ? 'live'
                                  : currPath === '/brands' &&
                                    menu.gnb_menu_name === '브랜드'
                                  ? 'current'
                                  : ''
                          }
                      >
                          ...생략
                      </li>
                  ))}
    );
}
profile
Superduper-India

0개의 댓글