← Back to Chapters

useNavigate, useLocation & useParams

? useNavigate, useLocation & useParams

? Quick Overview

React Router hooks allow components to navigate between routes, read URL details, and work with dynamic parameters in a clean and declarative way.

? Key Concepts

  • useNavigate() → Programmatic navigation
  • useLocation() → Read current URL info
  • useParams() → Extract dynamic route values

? Interactive Hook Simulator

Click the buttons to see how the simulated hooks update instantly.

? Browser URL: localhost:3000/
? useLocation().pathname: /
? useLocation().search:
? useParams(): {}

? Syntax & Theory

These hooks are provided by react-router-dom and can only be used inside functional components wrapped by a Router.

➡️ useNavigate()

? View Code Example
// Programmatic navigation using useNavigate
import React from "react";
import { useNavigate } from "react-router-dom";

function NavigateExample() {
  const navigate = useNavigate();

  const handleClick = () => {
    navigate("/about");
  };

  return (
    <div>
      <button onClick={handleClick}>Go to About</button>
    </div>
  );
}

export default NavigateExample;
? History Navigation
// Navigate backward and forward in history
navigate(-1);
navigate(1);

? useLocation()

? View Code Example
// Accessing current URL information
import React from "react";
import { useLocation } from "react-router-dom";

function LocationExample() {
  const location = useLocation();

  return (
    <div>
      <p>Path: {location.pathname}</p>
      <p>Query: {location.search}</p>
      <p>State: {JSON.stringify(location.state)}</p>
    </div>
  );
}

export default LocationExample;

? useParams()

? User Page Example
// Reading dynamic route parameters
import React from "react";
import { useParams } from "react-router-dom";

function UserPage() {
  const { id } = useParams();

  return (
    <div>
      <p>User ID: {id}</p>
    </div>
  );
}

export default UserPage;
? Route Configuration
// Defining routes with dynamic parameters
import React from "react";
import { Routes, Route } from "react-router-dom";
import UserPage from "./UserPage";

function App() {
  return (
    <Routes>
      <Route path="/user/:id" element={<UserPage />} />
    </Routes>
  );
}

export default App;

? Live Output / Explanation

Visiting /user/42 will display the value 42 dynamically inside the UserPage component.

? Tips & Best Practices

  • Use useNavigate for redirects after login or submit
  • Store temporary data in location.state
  • Keep route params short and meaningful
  • Combine all three hooks for advanced routing logic

? Try It Yourself

  1. Create routes like /product/:id
  2. Navigate using buttons instead of links
  3. Pass custom state during navigation
  4. Display query strings from the URL