What is the purpose of the useLocation hook in React Router and how can it be used effectively

0 votes
Can you tell me What is the purpose of the useLocation hook in React Router, and how can it be used effectively?
23 hours ago in Node-js by Ashutosh
• 27,610 points
14 views

1 answer to this question.

0 votes

The useLocation hook in React Router provides real-time access to the current URL information, including:

pathname (e.g., /dashboard)

search (query string like ?id=123)

hash (e.g., #settings)

state (data passed during navigation)

It automatically updates when the URL changes.

Effective Uses:

Track Page Changes

const { pathname } = useLocation();

useEffect(() => {

  console.log("Current page:", pathname); // Log route changes

}, [pathname]);

Read Query Parameters

const { search } = useLocation();

const id = new URLSearchParams(search).get("id"); // Gets "123" from ?id=123

Access Hidden Navigation Data

<Link to="/profile" state={{ user: "John" }}>Profile</Link>

const { state } = useLocation();

console.log(state.user); // "John"

answered 21 hours ago by anonymous

Related Questions In Node-js

0 votes
0 answers
0 votes
1 answer

What is the purpose of the Redirect component in React Router v5?

In React Router v5, the <Redirect /> ...READ MORE

answered 4 days ago in Node-js by anonymous
34 views
0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
0 votes
0 answers
0 votes
1 answer
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP