npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

nextjs-utils-hooks

v1.2.1

Published

A collection of useful hooks and utils built specifically for Next.js App Router.

Readme

nextjs-utils-hooks

A collection of useful React hooks and utilities built specifically for Next.js App Router.

npm version License: MIT npm downloads

📦 Installation

npm install nextjs-utils-hooks

or

yarn add nextjs-utils-hooks

or

pnpm add nextjs-utils-hooks

✨ Features

  • 🚀 Built specifically for Next.js 15+ App Router
  • 🎯 TypeScript support out of the box
  • 🪝 Collection of commonly used hooks
  • 🛠️ Useful utility functions for everyday tasks
  • 📦 Tree-shakeable
  • 🔧 Zero configuration required
  • ⚡ Lightweight and performant

🎯 Hooks

useIsClient

Detect if code is running on the client side. Useful for preventing hydration mismatches.

import { useIsClient } from "nextjs-utils-hooks";

function MyComponent() {
  const isClient = useIsClient();

  return <div>{isClient ? "Running on client" : "Running on server"}</div>;
}

useDebounce

Debounce any value with a customizable delay. Perfect for search inputs and API calls.

import { useDebounce } from "nextjs-utils-hooks";

function SearchComponent() {
  const [searchTerm, setSearchTerm] = useState("");
  const debouncedSearch = useDebounce(searchTerm, 500);

  useEffect(() => {
    // API call with debounced value
    if (debouncedSearch) {
      fetchResults(debouncedSearch);
    }
  }, [debouncedSearch]);

  return (
    <input
      value={searchTerm}
      onChange={(e) => setSearchTerm(e.target.value)}
      placeholder="Search..."
    />
  );
}

Parameters:

  • value: T - The value to debounce
  • delay?: number - Delay in milliseconds (default: 300)

useQueryParam

Manage URL query parameters with ease. Get and set query params with automatic URL updates.

import { useQueryParam } from "nextjs-utils-hooks";

function FilterComponent() {
  const [category, setCategory] = useQueryParam("category");

  return (
    <div>
      <p>Current category: {category || "none"}</p>
      <button onClick={() => setCategory("electronics")}>
        Set Electronics
      </button>
    </div>
  );
}

Returns: [value: string | null, setValue: (val: string) => void]

useWindowSize

Track window dimensions with automatic updates on resize.

import { useWindowSize } from "nextjs-utils-hooks";

function ResponsiveComponent() {
  const { width, height } = useWindowSize();

  return (
    <div>
      <p>
        Window size: {width} x {height}
      </p>
      {width < 768 ? <MobileView /> : <DesktopView />}
    </div>
  );
}

Returns: { width: number, height: number }

usePageLoad

Track page loading state during navigation. Combines loading state with React transitions.

import { usePageLoad } from "nextjs-utils-hooks";

function LoadingIndicator() {
  const isLoading = usePageLoad();

  return isLoading ? <Spinner /> : null;
}

Returns: boolean - true when page is loading

useRouteChange

Listen to route changes in Next.js App Router with customizable callbacks.

import { useRouteChange } from "nextjs-utils-hooks";

function MyLayout({ children }) {
  useRouteChange({
    onStart: (url) => {
      console.log("Navigation started to:", url);
      // Show loading indicator
    },
    onComplete: (url) => {
      console.log("Navigation completed to:", url);
      // Hide loading indicator, track analytics, etc.
    },
  });

  return <div>{children}</div>;
}

Parameters:

  • onStart?: (url: string) => void - Called when route change begins
  • onComplete?: (url: string) => void - Called when route change completes (with 100ms delay)

useServerAction

Manage server action state with loading and error handling. Perfect for forms and server mutations.

import { useServerAction } from "nextjs-utils-hooks";
import { submitForm } from "./actions";

function FormComponent() {
  const { runAction, loading, error } = useServerAction(submitForm);

  const handleSubmit = async (formData: FormData) => {
    await runAction(formData);
  };

  return (
    <form action={handleSubmit}>
      <input name="email" type="email" />
      <button disabled={loading}>{loading ? "Submitting..." : "Submit"}</button>
      {error && <p className="error">{error.message}</p>}
    </form>
  );
}

Returns:

  • runAction: (...args: Parameters<T>) => Promise<void> - Execute the server action
  • loading: boolean - Loading state
  • error: Error | null - Error object if action fails

🛠️ Utility Functions

getPlatform

Detect the user's platform based on the user agent string.

import { getPlatform } from "nextjs-utils-hooks";

function PlatformInfo() {
  const platform = getPlatform();
  
  return <div>You are using: {platform}</div>;
}

Returns: "mobile" | "windows" | "mac" | "linux" | "unknown"

isValidUrl

Validate if a string is a valid URL.

import { isValidUrl } from "nextjs-utils-hooks";

function LinkValidator() {
  const url = "https://example.com";
  const isValid = isValidUrl(url);
  
  return <div>{isValid ? "Valid URL" : "Invalid URL"}</div>;
}

Parameters:

  • url: string - The URL string to validate

Returns: boolean - true if valid URL, false otherwise

measureExecutionTime

Measure the execution time of a function in milliseconds.

import { measureExecutionTime } from "nextjs-utils-hooks";

function PerformanceTest() {
  const time = measureExecutionTime(() => {
    // Your code to measure
    for (let i = 0; i < 1000000; i++) {
      // Some computation
    }
  });
  
  console.log(`Execution took ${time}ms`);
}

Parameters:

  • fn: Function - The function to measure

Returns: number - Execution time in milliseconds

timeSince

Convert a date to a human-readable "time ago" format.

import { timeSince } from "nextjs-utils-hooks";

function PostTimestamp({ createdAt }: { createdAt: Date }) {
  return <span>{timeSince(createdAt)}</span>;
}

// Examples:
// timeSince(new Date(Date.now() - 5000)) // "just now"
// timeSince(new Date(Date.now() - 120000)) // "2 minutes ago"
// timeSince(new Date(Date.now() - 86400000)) // "1 day ago"

Parameters:

  • date: Date | string - The date to convert

Returns: string - Human-readable time difference (e.g., "2 hours ago", "just now")

scrollToElement

Smoothly scroll to an element on the page using a CSS selector.

import { scrollToElement } from "nextjs-utils-hooks";

function NavigationButton() {
  const handleClick = () => {
    scrollToElement("#contact-section");
  };
  
  return <button onClick={handleClick}>Scroll to Contact</button>;
}

Parameters:

  • selector: string - CSS selector of the element to scroll to

Returns: void

generateUUID

Generate a unique identifier (UUID v4).

import { generateUUID } from "nextjs-utils-hooks";

function CreateItem() {
  const handleCreate = () => {
    const id = generateUUID();
    console.log("New item ID:", id);
    // Use the ID for your item
  };
  
  return <button onClick={handleCreate}>Create New Item</button>;
}

Returns: string - A UUID v4 string (e.g., "550e8400-e29b-41d4-a716-446655440000")

🔧 Requirements

  • Next.js: 15.0.0 or higher
  • React: 19.0.0 or higher

📝 TypeScript

This package is written in TypeScript and includes type definitions out of the box. No need for @types/* packages.

🤝 Contributing

Contributions are welcome! Please feel free to submit a Pull Request.

📄 License

MIT © Ahmed Hashem

🐛 Issues

Found a bug? Please open an issue on GitHub.

📚 Changelog

See CHANGELOG.md for details on releases.


Made with ❤️ for the Next.js community