Skip to main content

Command Palette

Search for a command to run...

26) Route Params in React

Updated
View as Markdown
  1. What are Route Params?
    Route Params (or URL parameters) in React routing let you capture dynamic values from the URL and use them inside your components.
    They’re a core feature of React Router and are essential for building pages like user profiles, product details, blog posts, etc.

    import { Routes, Route } from "react-router-dom";
    
    <Routes>
      <Route path="/user/:id" element={<User />} />
    </Routes>
    

    :id → dynamic parameter
    Matches -
    /user/1 /user/42 /user/abc

  2. Accessing Route Params

    import { useParams } from "react-router-dom";
    
    const User = () => {
      const { id } = useParams();
    
      return <h2>User ID: {id}</h2>;
    }
    
  3. Important Points
    i) Params are always strings

    const { id } = useParams();
    console.log(typeof id); // string
    

    ii) Route must match exactly

    <Route path="/user/:id" />
    
  4. Advantages of Route Params
    Dynamic routing
    Reusable components
    Clean URLs
    Supports deep linking
    Essential for real-world apps

    const User = () => {
      const { id } = useParams();
      const [user, setUser] = useState(null);
    
      useEffect(() => {
        fetch(`/api/users/${id}`)
          .then(res => res.json())
          .then(data => setUser(data));
      }, [id]);
    
      return <div>{user?.name}</div>;
    }
    

    Route params are dynamic URL segments defined using : in React Router, allowing components to access and render data based on values in the URL using the useParams hook.