#useLocation in Next.jS 14
1 messages · Page 1 of 1 (latest)
In Next.js, there isn't a direct equivalent to react-router-dom's useLocation hook as seen in traditional React applications. However, Next.js provides its own routing capabilities through next/router or next/navigation for accessing the router object and its properties, which can serve similar purposes.
For Next.js 14, as per the extracts provided, there's a mention of using usePathname from next/navigation which can be considered for tracking changes in the pathname as an alternative to useLocation. Here's how you might adapt your existing useEffect to work with Next.js by using usePathname:
import { useEffect, useState } from 'react';
import { usePathname } from 'next/navigation';
export default function MyComponent() {
const pathname = usePathname();
const [navbarExpanded, setNavbarExpanded] = useState(true);
useEffect(() => {
setNavbarExpanded(false);
window.scrollTo({ top: 0, behavior: "smooth" });
}, [pathname]);
// Your component code
}
This approach uses usePathname to trigger effects based on the change of the pathname, similar to how you might use location from react-router-dom. Remember, this is specific to Next.js and leverages its built-in navigation hooks.
For more complex scenarios involving query parameters or full location objects, you might need to construct custom hooks or use additional properties and methods provided by next/router or next/navigation.