Performance: Conditional routes
Conditional routes affect page load speed and interaction responsiveness by controlling which pages or components load based on conditions.
import dynamic from 'next/dynamic'; const Dashboard = dynamic(() => import('./Dashboard')); const Login = dynamic(() => import('./Login')); export default function Page() { if (user.isLoggedIn) { return <Dashboard />; } else { return <Login />; } }
export default function Page() { if (user.isLoggedIn) { return <Dashboard />; } else { return <Login />; } }
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Static import of all routes | Low to medium (depends on components) | 1 per route render | Medium due to larger bundle | [X] Bad |
| Dynamic import with conditional rendering | Low (only needed components) | 1 per route render | Low due to smaller bundle | [OK] Good |
useRouter to access routing methods like push for redirects.useEffect runs side effects, useRouter is needed to actually change routes.isLoggedIn is false?import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Dashboard() {
const router = useRouter();
const isLoggedIn = false;
useEffect(() => {
if (!isLoggedIn) {
router.push('/login');
}
}, [isLoggedIn]);
return <h1>Dashboard</h1>;
}isLoggedIn is false, then calls router.push('/login').import { useRouter } from 'next/router';
import { useEffect } from 'react';
export default function Profile() {
const router = useRouter();
const isAuthorized = false;
if (!isAuthorized) {
router.push('/unauthorized');
}
return <h1>Profile</h1>;
}1. UseWhich combination correctly applies conditional routing best practice?useRouteranduseEffectto check login and redirect client-side.
2. Use Next.js middleware to check authentication before rendering.
3. Render a loading state while checking login status.
4. Avoid rendering protected content until login is confirmed.
Pass the test and this pattern moves unknown