Search code examples
reactjsnext.jsreact-router-dom

What re-places useLocation() in react-router-dom from Next.js next/navigation?


Recently, I migrated from React to Next.js version@14.0.4. In my website, I used states while pushing using useNavigate() and take value from another page using useLocation(). How can I do same thing in Next.js I am doing with query thing in Next.js but it is visible in link above, I even learned how to hide it but I cannot receive state from params anymore.

I tried lots of things and one example is here: link related to my question In here it says to use next/router, but in next.js version 14.0.4 says to use only next/navigation


Solution

  • See Migrating from next.router

    • The useRouter hook should be imported from next/navigation and not next/router when using the App Router
    • The pathname string has been removed and is replaced by usePathname()
    • The query object has been removed and is replaced by useSearchParams()
    • router.events has been replaced. See below.

    Follow the link/navigating part of the linked duplicate of the post you linked to, but follow the instructions above to use the correct useRouter, usePathname, and useSearchParams hooks if you are opting in to the new behavior in the app directory.

    Example:

    'use client'
    
    import { useRouter } from 'next/navigation';
    
    ...
    
    const router = useRouter();
    
    ...
    
    router.push("/somepath?param1=foo");
    
    'use client'
    
    import { useSearchParams } from 'next/navigation';
    
    ...
    
    const searchParams = useSearchParams();
    const param1 = searchParams.get("param1"); // "foo"