Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 13.6 — Protected Routes and Navigation UX
React · Example 3 of 3

React.lazy routes and ScrollToTop (declarative mode)

While Settings downloads, the page still shows Home, not the Suspense fallback: React Router wraps navigations in startTransition, and React keeps the old UI during a transition (Topic 14.3). The pathname (and the scroll effect) only changes once Settings is ready. The second visit doesn't download again.

Protect pages by redirecting logged-out users to a login page with <Navigate> (or redirect in a loader) and sending them back afterwards; load route code only when it's needed; and do what a full page load did for free: reset or restore scroll, move keyboard focus to the new content, and update the page title.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Make an AdminOnly layout route that lets through users with role === "admin", sends logged-out users to /login, and shows Not allowed (no redirect) to logged-in non-admins.

02

Write a safeFrom(value) function that returns value only if it's a local path, otherwise "/", and test it with "/orders", "//evil.example" and "https://evil.example".

03

Give three pages a React 19 <title> and log document.title after clicking between them in a memory router.

Explain it without notes

01

How do you build a protected route in React Router, and why use replace?

02

Why is a client-side auth guard not a security boundary?

03

How do lazy routes work in declarative and data mode, and what does the user see while code loads?

04

What must an SPA do after navigation that a full page load did automatically?

React.lazy routes and ScrollToTop (declarative mode)

Preview

Press Run to see the page.

Console

Nothing logged yet.

Expected console output

scrolled to top for /
downloading Settings...
while loading: Home
scrolled to top for /settings
after: Settings
scrolled to top for /
scrolled to top for /settings
second visit: Settings