Tutorials Logic, IN info@tutorialslogic.com
Navigation
Home About Us Contact Us Blogs FAQs
Tutorials
All Tutorials
Services
Academic Projects Resume Writing Website Development
Practice
Quiz Challenge Interview Questions Certification Practice
Tools
Online Compiler JSON Formatter Regex Tester CSS Unit Converter Color Picker
Compiler Tools

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

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
npm install react-router-dom
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
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
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
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
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
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
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

Many applications have routes that should only be visible to logged-in users. A common pattern is to check authentication and either render the page or redirect the user.

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
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.

Key Takeaways
  • React Router is used for client-side routing in React apps.
  • BrowserRouter enables routing for a typical web application.
  • Routes and Route define which component renders for a URL.
  • Link and NavLink are used for internal navigation.
  • Outlet renders child routes inside a layout route.
  • useParams reads dynamic values from the URL.
  • useNavigate allows programmatic navigation.
  • useSearchParams helps work with query strings.

Ready to Level Up Your Skills?

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