Using useRouter for Conditional Rendering in Next.js

The useRouter hook from Next.js allows you to access route info inside your components. You can use it for conditional rendering based on the current route.

Why Use useRouter?

Sometimes, you want to hide/show content depending on the route—like hiding a header on the login page

import { useRouter } from 'next/router';


export default function Layout({ children }) {
  const router = useRouter();
  const isAuthPage = router.pathname === '/login';


  return (
    <>
      {!isAuthPage && <Header />}
      {children}
    </>
  );
}

Conclusion

The useRouter hook gives you control over route-based behavior and improves flexibility when structuring components.

Leave a comment

Your email address will not be published. Required fields are marked *