Navigation is a basic facet of net growth, particularly in ReactJS functions. As a newbie, understanding the best way to handle routes and entry details about the present URL is essential. On this beginner-friendly information, we are going to delve into the world of React Router DOM and demystify certainly one of its highly effective instruments – the useLocation hook. We’ll break down its significance, talk about its utilization, and supply sensible examples that will help you grasp this idea effortlessly.

Understanding the Fundamentals:

Earlier than we dive into the code, let’s grasp the fundamentals. In ReactJS functions, navigation between totally different pages or elements typically requires understanding the present URL. React Router DOM is a well-liked library that simplifies this course of, and the useLocation hook is a key device it gives.

What’s useLocation?

In React Router DOM, the useLocation hook gives entry to the present location object. This object comprises worthwhile details about the present URL, similar to path names, question parameters, and extra. Understanding and using this data can considerably improve the person expertise of your net utility.

How you can Use useLocation:

Let’s discover a easy instance as an example the utilization of the useLocation hook:

import React from "react";
import {
  BrowserRouter as Router,
  Route,
  Hyperlink,
  Swap,
  useLocation
} from "react-router-dom";


// Hoem element code 
const House = () => {
  const location = useLocation();
  console.log(location);
  return (
    <div>
      <h3> Welcome to the House Web page!</h3>
      <h1>House Web page {location.pathname}</h1>
      <p>Present Path: {location.pathname}</p>
      <p>Search Parameters: {location.search}</p>
    </div>
  );
};

// About element code 
const About = () => {
  const location = useLocation();
  console.log(location);

  return (
    <div>
      <h3> Welcome to the About Web page!</h3>
      <h1>About Web page {location.pathname}</h1>
      <p>Present Path: {location.pathname}</p>
      <p>Search Parameters: {location.search}</p>
    </div>
  );
};


// Contact element code
// Observe similar as above house and about element on Contact element
const Contact = () => <h1>Contact Us</h1>;




const NotFound = () => <h1>404 - Web page Not Discovered</h1>;

const App = () => {
  return (
    <Router>
      <nav model={{ show: "flex", hole: "20px" }}>
        <Hyperlink to="/house">House</Hyperlink>
        <Hyperlink to="/about">About</Hyperlink>
        <Hyperlink to="/contact">Contact</Hyperlink>
      </nav>

      <Swap>
        <Route precise path="/house" element={House} />
        <Route path="/about" element={About} />
        <Route path="/contact" element={Contact} />
        <Route element={NotFound} />
      </Swap>
    </Router>
  );
};

export default App;

Enter fullscreen mode

Exit fullscreen mode

Try and Discover Above
https://codesandbox.io/s/uselocation-reactjs-7jkgd3?file=/src/App.js

On this instance, we import the useLocation hook and make the most of within the About element to entry the situation object similar to pathname and search. By accessing location.pathname and location.search, we are able to show the present path and search parameters, respectively.
The Route elements outline the paths and their corresponding elements throughout the Swap element, which ensures that just one route is rendered at a time.

Present location object for About element :-

{pathname: "/about", search: "", hash: "", state: undefined, key: "bhlp93"}
pathname: "/about"
search: ""
hash: ""
state: undefined
key: "bhlp93"
Enter fullscreen mode

Exit fullscreen mode

Actual-World Software:

Think about you are constructing an e-commerce web site. Utilizing the useLocation hook, you possibly can dynamically render totally different product particulars based mostly on the route and question parameters. As an illustration, displaying particular product data when a person selects a selected merchandise from the URL.
We will then make the most of properties of the situation object, similar to pathname and search, to show details about the present route.
The Route elements outline the paths and their corresponding elements throughout the Swap element, which ensures that just one route is rendered at a time.

Finest Practices:

  • Part Placement: Make sure that you employ the useLocation hook inside a element that’s rendered inside a <Router> element. This ensures entry to the present location object.

  • Keep away from Overuse: Whereas the useLocation hook is highly effective, keep away from extreme reliance on it for advanced logic or enterprise guidelines. As a substitute, use it to assemble data and cross it to different elements or features.

  • Optimize Efficiency: Be conscious of efficiency impacts, particularly when utilizing the useLocation hook in deeply nested elements. Think about optimizing rerenders if obligatory.

Conclusion:

Understanding the useLocation hook in React Router DOM is important for constructing dynamic and responsive net functions. By harnessing its energy, you possibly can create seamless navigation experiences, whether or not you’re constructing an e-commerce platform, a weblog, or some other sort of net utility. As you proceed your ReactJS journey, keep in mind that mastering the basics of navigation is a key step towards turning into a proficient React developer.

Be at liberty to experiment with the useLocation hook in your tasks, and don’t hesitate to discover its full potential. Glad coding!

source