DEV Community

JAKER HOSSAIN
JAKER HOSSAIN

Posted on

1

Next.js Path Extractor: Custom Hook for URL Paths & Query Parameters

Introducing usePathExtractor – a custom React hook for Next.js that simplifies extracting and managing URL paths, query parameters, and active route states. It helps developers efficiently work with dynamic routing, making navigation handling more intuitive.

"use client";

import { usePathname, useSearchParams } from "next/navigation";
import { useMemo } from "react";

export const usePathExtractor = () => {
  const pathname = usePathname();
  const searchParams = useSearchParams();

  const queryParams = useMemo(() => {
    const params: Record<string, string | string[]> = {};
    searchParams.forEach((value, key) => {
      if (params[key]) {
        params[key] = Array.isArray(params[key])
          ? [...params[key], value]
          : [params[key], value];
      } else {
        params[key] = value;
      }
    });
    return params;
  }, [searchParams]);

  const fullUrl = useMemo(() => {
    if (typeof window !== "undefined") {
      return window.location.href;
    }
    return "";
  }, []);

  const basePath = useMemo(() => {
    return pathname.split("/").slice(0, 2).join("/");
  }, [pathname]);

  const isActiveRoute = (route: string) => {
    return pathname.startsWith(route);
  };

  return {
    pathname,
    fullUrl,
    basePath,
    queryParams,
    isActiveRoute,
  };
};

Enter fullscreen mode Exit fullscreen mode

Benefits:
✅ Effortless Query Parameter Extraction – Converts search params into an easily accessible object.
✅ Retrieve Full URL – Get the complete URL directly from the hook.
✅ Base Path Management – Extract the main route without extra logic.
✅ Active Route Detection – Easily check if a route is currently active.

Perfect for building dynamic dashboards, filtering systems, and improving navigation handling in Next.js projects! 🚀

Image of Stellar post

How a Hackathon Win Led to My Startup Getting Funded

In this episode, you'll see:

  • The hackathon wins that sparked the journey.
  • The moment José and Joseph decided to go all-in.
  • Building a working prototype on Stellar.
  • Using the PassKeys feature of Soroban.
  • Getting funded via the Stellar Community Fund.

Watch the video

Top comments (0)

👋 Kindness is contagious

Dive into this insightful write-up, celebrated within the collaborative DEV Community. Developers at any stage are invited to contribute and elevate our shared skills.

A simple "thank you" can boost someone’s spirits—leave your kudos in the comments!

On DEV, exchanging ideas fuels progress and deepens our connections. If this post helped you, a brief note of thanks goes a long way.

Okay