Tutorials Logic, IN info@tutorialslogic.com

React Router v6 Routes, Link, useNavigate, useParams: Tutorial, Examples, FAQs & Interview Tips

React Router v6 Routes, Link, useNavigate, useParams

React Router v6 Routes, Link, useNavigate, useParams is an important React JS topic because it appears in real projects, debugging sessions, and interviews. Learn the meaning first, then connect it to a small working example so the rule does not stay abstract.

For this page, focus on what problem React Router v6 Routes, Link, useNavigate, useParams solves, where developers usually make mistakes, and how to verify the result. The audit note for this lesson was: limited checklist/practice/mistake/FAQ notes .

A strong understanding of React Router v6 Routes, Link, useNavigate, useParams should include syntax, behavior, one realistic use case, one failure case, and one quick way to check your work with tools or output.

React Router v6 Routes Link useNavigate useParams should be studied as a practical React application development lesson, not as a label. Start by naming the input, the rule that changes the input, and the result a learner should be able to predict after reading the page.

In the react-js > react-router page, the notes should connect the definition with a working scenario, a mistake that beginners actually make, and the exact check that proves the fix. That makes the topic useful for coding, debugging, and interview revision.

What is React Router?

React Router is the most common routing library for React applications. It allows users to move between different pages or views without reloading the entire browser page. This is called client-side routing.

In a traditional multi-page website, clicking a link usually requests a new HTML page from the server. In a React single-page application, React Router updates the URL and changes which components are shown, while the app stays loaded in the browser.

This makes navigation feel faster and smoother, and it helps React apps behave more like desktop applications.

Why Routing Matters

  • Users can visit different sections of the app with clear URLs
  • Pages can be bookmarked and shared
  • Navigation feels smooth without full page reloads
  • Large apps can be organized into multiple screens
  • Dynamic URLs can represent user IDs, slugs, categories, and more

Installing and Setting Up React Router

To use React Router in a normal React app, install react-router-dom. Then wrap the app with BrowserRouter.

Initial Setup

Initial Setup
npm install react-router-dom

Installing and Setting Up React Router

Installing and Setting Up React Router
import ReactDOM from 'react-dom/client'
import { BrowserRouter } from 'react-router-dom'
import App from './App'

ReactDOM.createRoot(document.getElementById('root')).render(
    <BrowserRouter>
        <App />
    </BrowserRouter>
)

Defining Routes

Routes tell React Router which component should be rendered for a given URL. In React Router v6, routes are usually defined with Routes and Route.

Basic Routes

Basic Routes
import { Routes, Route } from 'react-router-dom'

function Home() {
    return <h1>Home Page</h1>
}

function About() {
    return <h1>About Page</h1>
}

function Contact() {
    return <h1>Contact Page</h1>
}

function App() {
    return (
        <Routes>
            <Route path="/" element={<Home />} />
            <Route path="/about" element={<About />} />
            <Route path="/contact" element={<Contact />} />
        </Routes>
    )
}

Navigating with Link and NavLink

In React Router, you normally use Link instead of a plain a tag for internal navigation. A plain anchor triggers a full page reload, while Link performs client-side navigation.

NavLink is similar to Link, but it can style the active route automatically. That makes it very useful for menus and navigation bars.

Navigation Links

Navigation Links
import { Link, NavLink } from 'react-router-dom'

function Navbar() {
    return (
        <nav>
            <Link to="/">Home</Link>
            <NavLink
                to="/about"
                className={({ isActive }) => isActive ? 'active-link' : ''}
            >
                About
            </NavLink>
            <NavLink to="/contact">Contact</NavLink>
        </nav>
    )
}

Nested Routes and Layouts

Many apps share a common layout across several pages, such as a header, sidebar, and footer. React Router supports this with nested routes and the Outlet component.

Nested Routes with Outlet

Nested Routes with Outlet
import { Routes, Route, Outlet } from 'react-router-dom'

function Layout() {
    return (
        <div>
            <header>My Website</header>
            <main>
                <Outlet />
            </main>
        </div>
    )
}

function Home() {
    return <h2>Home</h2>
}

function About() {
    return <h2>About</h2>
}

function App() {
    return (
        <Routes>
            <Route path="/" element={<Layout />}>
                <Route index element={<Home />} />
                <Route path="about" element={<About />} />
            </Route>
        </Routes>
    )
}

Route Parameters

Route parameters allow the URL to include dynamic values. For example, /users/5 and /users/9 can both use the same route pattern /users/:id.

useParams Example

useParams Example
import { Route, Routes, useParams } from 'react-router-dom'

function UserDetail() {
    const { id } = useParams()
    return <h2>User ID: {id}</h2>
}

function App() {
    return (
        <Routes>
            <Route path="/users/:id" element={<UserDetail />} />
        </Routes>
    )
}

Programmatic Navigation

Sometimes navigation should happen after an action such as logging in, saving data, or submitting a form. In those cases, you can navigate in code using the useNavigate hook.

useNavigate Example

useNavigate Example
import { useNavigate } from 'react-router-dom'

function LoginForm() {
    const navigate = useNavigate()

    const handleLogin = () => {
        // pretend login succeeded
        navigate('/dashboard')
    }

    return <button onClick={handleLogin}>Login</button>
}

Query Strings with useSearchParams

Some pages use query strings such as ?q=react&page=2. React Router provides useSearchParams to read and update those values.

useSearchParams Example

useSearchParams Example
import { useSearchParams } from 'react-router-dom'

function SearchPage() {
    const [searchParams, setSearchParams] = useSearchParams()
    const query = searchParams.get('q') || ''

    return (
        <div>
            <input
                value={query}
                onChange={(e) => setSearchParams({ q: e.target.value })}
                placeholder="Search..."
            />
            <p>Current query: {query}</p>
        </div>
    )
}

Protected Routes

Protected routes gate a screen behind an authentication check. In React Router, the route usually renders its element only when the session is valid; otherwise it redirects to sign-in or shows an access state that explains why the page is unavailable.

Protected Route Example

Protected Route Example
import { Navigate } from 'react-router-dom'

function ProtectedRoute({ isLoggedIn, children }) {
    if (!isLoggedIn) {
        return <Navigate to="/login" replace />
    }

    return children
}

function App() {
    const isLoggedIn = false

    return (
        <Routes>
            <Route
                path="/dashboard"
                element={
                    <ProtectedRoute isLoggedIn={isLoggedIn}>
                        <Dashboard />
                    </ProtectedRoute>
                }
            />
        </Routes>
    )
}

404 Routes

A wildcard route with * can be used to show a "Page Not Found" screen when no other route matches.

Not Found Route

Not Found Route
function NotFound() {
    return <h2>404 - Page Not Found</h2>
}

function App() {
    return (
        <Routes>
            <Route path="*" element={<NotFound />} />
        </Routes>
    )
}

Best Practices for React Router

  • Use Link and NavLink for internal navigation
  • Keep route definitions organized and readable
  • Use nested layouts to avoid repeated page structure
  • Use route parameters for dynamic pages like users and blog posts
  • Add a 404 route so unknown URLs are handled gracefully
  • Use protected routes for authenticated sections

Common Mistakes

  • Using plain anchor tags for internal app links
  • Forgetting to wrap the app in BrowserRouter
  • Mixing route paths and nested layout structure incorrectly
  • Forgetting to add an Outlet in layout components
  • Not handling unknown URLs with a wildcard route

Summary

React Router gives React applications meaningful URLs and smooth navigation without full page reloads. It helps organize an application into screens, supports layouts, route parameters, query strings, protected routes, and not found pages, and makes large React apps much easier to structure.

Once you understand the core pieces such as BrowserRouter, Routes, Route, Link, NavLink, Outlet, and the routing hooks, you can build multi-page React experiences with confidence.

React Router v6 Routes Link useNavigate useParams state check

React Router v6 Routes Link useNavigate useParams state check
const state = { topic: "React Router v6 Routes Link useNavigate useParams", ready: true };
if (state.ready) {
  console.log(state.topic + ": render or run the normal path");
}

React Router v6 Routes Link useNavigate useParams fallback check

React Router v6 Routes Link useNavigate useParams fallback check
const response = null;
const message = response?.message ?? "React Router v6 Routes Link useNavigate useParams: show a clear fallback";
console.log(message);
Key Takeaways
  • Explain the purpose of React Router v6 Routes, Link, useNavigate, useParams before memorizing syntax.
  • Run or trace one small React JS example and confirm the output.
  • Test one normal case, one edge case, and one mistake case for React Router v6 Routes, Link, useNavigate, useParams.
  • Write the rule in your own words after checking the example.
  • Connect React Router v6 Routes, Link, useNavigate, useParams to a real project scenario instead of treating it as an isolated definition.
Common Mistakes to Avoid
WRONG Memorizing React Router v6 Routes Link useNavigate useParams without the situation where it is useful.
RIGHT Connect React Router v6 Routes Link useNavigate useParams to a concrete React application development task.
Purpose makes syntax easier to recall.
WRONG Testing React Router v6 Routes Link useNavigate useParams only with the perfect input.
RIGHT Include empty, missing, duplicate, incompatible, or failed cases when relevant.
Real bugs usually appear outside the perfect path.
WRONG Changing code before reading the visible symptom or error message.
RIGHT Inspect the output, state, configuration, or stack trace connected to React Router v6 Routes Link useNavigate useParams.
Evidence keeps debugging focused.
WRONG Memorizing React Router v6 Routes Link useNavigate useParams without the situation where it is useful.
RIGHT Connect React Router v6 Routes Link useNavigate useParams to a concrete React application development task.
Purpose makes syntax easier to recall.

Practice Tasks

  • Modify the example so it handles a different input or condition.
  • Write one mistake related to React Router v6 Routes, Link, useNavigate, useParams, then fix it and explain the fix.
  • Summarize when to use React Router v6 Routes, Link, useNavigate, useParams and when another approach is better.
  • Write a small example that uses React Router v6 Routes Link useNavigate useParams in a realistic React application development scenario.
  • Change one important value in the React Router v6 Routes Link useNavigate useParams example and predict the result first.

Frequently Asked Questions

The common mistake is memorizing syntax without understanding when the behavior changes or fails.

Remember the problem it solves in React application development, then attach the syntax or steps to that problem.

You can predict the result of a small example, explain a failure case, and choose it over a nearby alternative for a clear reason.

They often copy the syntax but skip the state, input, dependency, selector, route, type, or configuration that controls the behavior.

Ready to Level Up Your Skills?

Explore 500+ free tutorials across 20+ languages and frameworks.