Yuko
Posted on May 28, 2023
This is a series of my memo from when I migrated Next.js v13 into my project with the article From Pages to App. I also updated other packages’ versions.
Part1: Migrated app router from page router
Part2: Migrated router API
Part3: Applied some other Next.js v13 updates
Optional: Updated NextAuth from v3 to v4
Optional: Updated Redux from classical Redux to Redux Toolkit Query
useRouter, usePathname, and useSearchParam are available from next/navigation. This useRouter behaves differently from the same name hook from next/router. withRouter is also not available for App router.
From Pages to App
useRouter
// Before
import { useRouter } from "next/router";
// After
import { useRouter } from "next/navigation";
withRouter
You can use each hook depending on what you need.
For example, I used usePathname instead of router.query provided from withRouter.
// Before
import { withRouter } from "next/router";
const CategoryPage = ({ router }) => {
...skip
const categoryObject = list.filter(
(category) => category.path === router.query.category
)[0];
... rest
};
export default withRouter(CategoryPage);
// After
import usePathnameArray from "../../../client/hooks/use-pathname-array";
const CategoryPage = () => {
const pathnameArray = usePathnameArray();
...skip
const categoryObject = categories.filter(
(category) => category.path === pathnameArray[2]
)[0];
...rest
};
export default CategoryPage;
"use client";
import { usePathname } from "next/navigation";
/**
* return pathnames split with /
* e.g /shop/womens-clothing => ["", "shop", "womens-clothing"]
* @returns {string[]}
*/
const usePathnameArray = () => {
const pathname = usePathname();
return pathname.split("/");
};
export default usePathnameArray;
original article is here
Posted on May 28, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
November 29, 2024
November 27, 2024