DEV Community

builtbyjosh
builtbyjosh

Posted on

What is useParams()?

useParams() is part of a set of hooks that ships with react-router-dom along with useHistory, useLocation, and useRouteMatch. It is defined as:

useParams returns an object of key/value pairs of URL parameters. Use it to access match.params of the current .

But what does it mean and how do you implement useParams() into your React project.

Because useParams ships with react-router-dom, it works directly with your route paths. With useParams, your params have to match the path set in your route:

<Route path=’/users/:username’>
Enter fullscreen mode Exit fullscreen mode

With this route, you are able to access the :username param from the URL. To use this param, you must first import the useParams() hook into your app and create a variable within your component.

Import { useParams } from “react-router-dom”

const App = () => {
    let { username } = useParams();
    return <div>My name is {username}</div>
}
Enter fullscreen mode Exit fullscreen mode

Now you can dynamically change the component based on any URL passed that matches the declared route. This can also be used for API calls. If you have a list of users, you can click one user’s name and fetch all of their information with their name as the search term that is added to the end of the fetch URL.

Top comments (0)