📌 useLocation in React -🙏 Namaste React

0
useLocation in React: Master Dynamic Routing | Complete Guide 2024

useLocation in React: Complete Guide to Dynamic Route Handling

useLocation Hook in React

Understanding useLocation Hook

The useLocation hook is used to track the current location in a React application. This is especially helpful in cases where you need to dynamically adjust the UI based on the user's current location in the app.

For example, when you're in the Home tab of a navigation bar, you might display a distinct home icon. This behavior can be implemented using the useLocation hook.

Overview

The useLocation hook provides access to the current location object, which contains the following properties:

  1. pathname: Represents the main route of the URL.
  2. search: Contains query parameters from the URL.
  3. hash: Refers to the anchor tag part of the URL, used to navigate within sections of a page.

Implementation

To use the useLocation hook:

  1. Import it from the react-router-dom package:
import { useLocation } from "react-router-dom";
  1. Initialize it in your component:
const location = useLocation();

That's it! You can now use the location object to access pathname, search, and hash properties.

Detailed Breakdown

1. Pathname

The pathname property gives the path of the current URL.

Example:
URL: https://sudipsharma.com.np/isgreat
location.pathname"isgreat"

2. Search

The search property holds query parameters from the URL. These parameters follow the ? symbol.

Example:
URL: https://sudipsharma.com.np/isgreat?jsCoder
location.search"jsCoder"

3. Hash

The hash property is used for navigation within a single page (e.g., linking to a specific section). It captures the value after the # symbol.

Example:
URL: https://sudipsharma.com.np/isgreat#profile
location.hash"profile"

You can use the hash to navigate or redirect users to specific sections of the page based on an ID.

Real-World Use Case

Imagine you have a scenario where you need to determine whether the current page is the user profile. Based on this, you can make the corresponding navigation bar tab active.

Example Implementation:

// Import useLocation hook
import { useLocation } from "react-router-dom";

// Create Navbar component
const Navbar = () => {
  // Initialize useLocation
  const location = useLocation();

  // Get URL parameters
  const urlParams = new URLSearchParams(location.search);
  const tab = urlParams.get("tab");
  
  // Example URL: https://sudipsharma.com.np/?tab=profile
  console.log(tab); // Output: "js"

  // Render navigation with conditional className
  return (
    <nav>
      <button class="${tab === 'profile' ? 'active' : ''}">
        Profile
      </button>
    </nav>
  );
};

In this example, the button's class will be "active" when the URL parameter "tab" equals "profile".

Additional Notes

Dynamic Functionality

Use the URLSearchParams object to manipulate query strings dynamically. You can fetch, set, or remove query parameters to make the app responsive and interactive.

Flexibility

The useLocation hook works seamlessly with routing to enhance user navigation, tracking, and dynamic rendering.

Frequently Asked Questions

1. What is the difference between useNavigate and useLocation?

  • useNavigate: This hook is used to programmatically navigate to different routes in your application. It is primarily used for redirection.
  • useLocation: This hook provides the current location object, allowing you to track and access details about the current URL (like pathname, search, and hash).

2. Will useLocation make the URL dynamically usable?

Yes, useLocation allows you to dynamically fetch and use information from the URL. It can adapt based on the query parameters, hash, or pathname, making the application more interactive.

3. Which is better to use: search or hash?

It depends on the use case:

  • Use search if you need to handle query parameters for data fetching, filtering, or dynamic updates.
  • Use hash for navigation within the same page, such as scrolling to specific sections.

If You Face Any Issues, Feel Free to Connect With Me

Post a Comment

0Comments
Post a Comment (0)
To Top