๊ฐœ๋ฐœ/Next.js

Next.js14์—์„œ useRouter ์‚ฌ์šฉํ•˜๊ธฐ

๋ฐ(Ming) ๐Ÿˆ‍โฌ› 2024. 1. 3. 15:00
728x90
๋ฐ˜์‘ํ˜•

 

nextjs12 ๋ฅผ ์“ฐ๋‹ค๊ฐ€ nextjs14๋กœ ๊ธ‰ ์ ํ”„๋ฅผ ํ•˜๋‹ค๋ณด๋‹ˆ ์ƒˆ๋กœ์šด ๊ฒƒ๋“ค์ด ๊ฝค ๋ˆˆ์— ๋“ค์–ด์™”๋‹ค. ํ•ด๋‹น ๋‚ด์šฉ์€ nextjs13 ์ดํ›„์—๋„ ์ ์šฉ์ด ๋˜๋Š” ๋‚ด์šฉ์ด๋‹ค. ํŽ˜์ด์ง€๋ฅผ ๋ฆฌ๋กœ๋“œํ•˜๋ ค๊ณ ํ•˜๋Š”๋ฐ, reload() ํ•จ์ˆ˜๊ฐ€ ์—†์–ด์ง„๊ฒƒ ์•„๋‹ˆ๊ฒ ๋Š”๊ฐ€! 

๊ทธ๋ž˜์„œ ๊ณต์‹๋ฌธ์„œ๋ฅผ ์ฐพ์•„๋“ค์–ด๊ฐ”๋‹ค. ๊ณต์‹๋ฌธ์„œ ์›๋ณธ์„ ์ข€ ๊ฐ€์ ธ์™€๋ดค๋‹ค. 

 

useRouter()

  • router.push(href: string, { scroll: boolean }):
    Perform a client-side navigation to the provided route. Adds a new entry into the browser’s history stack.
    "use client" ๋ฅผ ์‚ฌ์šฉํ•œ client-side๋กœ route๋ฅผ ์ œ๊ณตํ•  ๋•Œ ์‚ฌ์šฉ
  • router.replace(href: string, { scroll: boolean }): Perform a client-side navigation to the provided route without adding a new entry into the browser’s history stack.
    ์—ญ์‹œ๋‚˜ client components ์—์„œ ๋ผ์šฐํŠธ ์“ธ ๋•Œ ์‚ฌ์šฉ - 
  • router.refresh(): Refresh the current route. Making a new request to the server, re-fetching data requests, and re-rendering Server Components. The client will merge the updated React Server Component payload without losing unaffected client-side React (e.g. useState) or browser state (e.g. scroll position).
    reload()๋ฅผ ์“ฐ์ง€ ์•Š๊ณ   ํŽ˜์ด์ง€ ๋ฆฌ๋กœ๋“œ๊ฐ€ ํ•„์š”ํ•  ์‹œ์— ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ๋‹ค. ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ ๋ฆฌ๋ Œ๋”๋ง์ด ๋œ๋‹ค. 
  • router.prefetch(href: string): Prefetch the provided route for faster client-side transitions.
    href์— ๋Œ€ํ•œ ํŽ˜์ด์ง€ prefetch ํ•˜์—ฌ ๋”์šฑ ๋น ๋ฅธ ํด๋ผ์ด์–ธํŠธ ์‚ฌ์ด๋“œ ํŽ˜์ด์ง€ ์ „ํ™˜์„ ๊ตฌํ˜„ํ•  ์ˆ˜ ์žˆ๋‹ค
  • router.back(): Navigate back to the previous route in the browser’s history stack.
  • router.forward(): Navigate forwards to the next page in the browser’s history stack.

 

 

Migrating from next/router

  • The useRouter hook should be imported from next/navigation and not next/router when using the App Router
    import ํ•  ๋•Œ 'next/router' ๊ฐ€ ์•„๋‹ˆ๋ผ 'next/navigation' ์„ ์‚ฌ์šฉํ•ด์•ผํ•œ๋‹ค.
  • The pathname string has been removed and is replaced by usePathname()
    pathname ๋ฌธ์ž๋Š” ์—†์–ด์ง€๊ณ  usePathname์œผ๋กœ ๋ณ€๊ฒฝ๋จ!
  • The query object has been removed and is replaced by useSearchParams()
    query object ์—ญ์‹œ ์—†์–ด์ง€๊ณ  useSearchParams๋กœ ๋ณ€๊ฒฝ๋จ
  • router.events has been replaced. 

 

์œ„์˜ ์˜๋ฌธ ์›๋ณธ์„ ๋ณด์‹ค ์ˆ˜ ์žˆ๋Š” ๊ณต์‹๋ฌธ์„œ ์ฃผ์†Œ!

 

  • ๊ณต์‹๋ฌธ์„œ

https://nextjs.org/docs/app/api-reference/functions/use-router

 

Functions: useRouter | Next.js

API reference for the useRouter hook.

nextjs.org

 

 

 

 

728x90