iTranslated by AI

The content below is an AI-generated translation. This is an experimental feature, and may contain errors. View original article
🚀

Summary of nuqs 2.5.0 Updates

に公開

Introduction 🚀

On August 22, 2024, version 2.5.0 of nuqs, a type-safe URL state management library, was released.

https://nuqs.47ng.com/blog/nuqs-2.5

After seven beta releases, this version adds many useful features.
The most notable new features include:

  • Debounce functionality to control URL updates for high-frequency input
  • Key Isolation to optimize component re-rendering
  • Standard Schema for type inference and runtime validation
  • Experimental support for TanStack Router

This article introduces these new features.

Debounce Feature ⏱️

One of the most notable features in nuqs 2.5.0 is the Debounce functionality via the limitUrlUpdates option. This feature enables more precise URL update control compared to the previous throttleMs option.

In search forms and filter features, updating the URL on every user input can cause problems such as processing load from frequent URL updates, dozens of API calls per second, and history entry bloat when using history: 'push'.

nuqs supports both debounce() and throttle(), allowing you to choose based on your use case. Debounce is suitable for search forms because it prioritizes the last input, while Throttle is suitable for sliders and real-time updates because it provides continuous feedback.

For detailed implementation and code examples, please refer to the following article.

https://zenn.dev/chot/articles/ae1d907c72d6e3

Key Isolation 🔗

Overview

Key Isolation is a performance optimization feature introduced in nuqs 2.5.0. With this feature, components re-render only when the URL parameter they manage changes.

In traditional implementations, any URL parameter change could cause all components using nuqs to re-render. Key Isolation solves this problem and improves performance in large applications.

Supported Frameworks

Key Isolation is supported in the following frameworks:

  • React SPA
  • React Router
  • Remix
  • TanStack Router

Basic Usage

Key Isolation works automatically, so no special configuration is needed.

function ProductFilters() {
  const [category, setCategory] = useQueryState('category', parseAsString)
  const [sort, setSort] = useQueryState('sort', parseAsString)

  // Re-render only when category or sort changes
  console.log('ProductFilters rendered')

  return (
    <div>
      <select value={category || ''} onChange={(e) => setCategory(e.target.value)}>
        <option value="">All</option>
        <option value="electronics">Electronics</option>
      </select>
      <select value={sort || ''} onChange={(e) => setSort(e.target.value)}>
        <option value="">Sort order</option>
        <option value="price">By price</option>
      </select>
    </div>
  )
}

Performance Effect

Key Isolation prevents unnecessary re-renders.

Traditional behavior

/?category=electronics changed
↓
All components using nuqs re-render
- ProductFilters ✅ (necessary)
- Other components ❌ (unnecessary)

With Key Isolation enabled

/?category=electronics changed
↓
Only components using the category parameter re-render
- ProductFilters ✅ (necessary)
- Other components ⏸️ (no change)

Standard Schema 📋

Overview

Standard Schema is a validation feature introduced in nuqs 2.5.0. This feature allows you to create Standard Schema compatible validators from search parameter definitions.

Standard Schema is a specification that provides a common interface among TypeScript validation libraries. By adopting this specification, nuqs simplifies integration with other tools such as tRPC and TanStack Router.

Basic Usage

import {
  createStandardSchemaV1,
  parseAsInteger,
  parseAsString,
} from 'nuqs' // or 'nuqs/server'

// 1. Define search parameters as usual
export const searchParams = {
  searchTerm: parseAsString.withDefault(''),
  maxResults: parseAsInteger.withDefault(10),
  category: parseAsString
}

// 2. Create a Standard Schema compatible validator
// → Reusable with type safety in tRPC, TanStack Router, etc.
export const validateSearchParams = createStandardSchemaV1(searchParams)

Integration with tRPC

Standard Schema enables direct use of nuqs search parameter definitions in tRPC procedures.

import { router, publicProcedure } from './trpc'
import { validateSearchParams } from './search-params'

export const appRouter = router({
  // 3. Use directly in tRPC procedures
  // → API validation is performed with the same type definitions as the frontend URL state
  search: publicProcedure
    .input(validateSearchParams)
    .query(async ({ input }) => {
      // input is type-safe with searchTerm, maxResults, and category properties
      const { searchTerm, maxResults, category } = input

      // Database query and other logic
      return await searchProducts({
        query: searchTerm,
        limit: maxResults,
        category
      })
    }),

  getProductCategories: publicProcedure
    .query(async () => {
      return await getCategories()
    })
})

export type AppRouter = typeof appRouter

Effects of Standard Schema

Standard Schema makes it possible to generate validators usable by other tools from nuqs parser definitions.

Key Benefits

  1. Interoperability across tools

    • Reuse the same validation logic in various libraries such as tRPC, TanStack Form, TanStack Router, etc.
    • Achieve "write once, validate everywhere"
  2. Consistent type safety

    • Type definitions automatically flow from frontend URL state to backend APIs
    • TypeScript's type inference is shared across tools
  3. Improved developer experience

    • Eliminates the need to create adapters for each library
    • Manage URL parameter definitions in one place and reuse them across multiple contexts

Standard Schema is being developed as a standard specification, with major validation libraries like Zod, Valibot, and ArkType implementing a common interface to unify the ecosystem.

TanStack Router Support 🛣️

nuqs 2.5.0 adds experimental support for TanStack Router. This feature is currently in beta and positioned as a complementary capability.

Note

This support is intended for compatibility with external libraries that use nuqs and is typically not needed for TanStack Router applications themselves. Since TanStack Router already provides an excellent type-safe URL state management API, it is generally recommended to use that instead.

Reference: https://x.com/nuqs47ng/status/1959166202036490354

Setup

To use nuqs, configure a dedicated adapter as with other frameworks.

// app/root.tsx (TanStack Router)
import { NuqsAdapter } from 'nuqs/adapters/tanstack-router'
import { Outlet } from '@tanstack/react-router'

export default function App() {
  return (
    <NuqsAdapter>
      <Outlet />
    </NuqsAdapter>
  )
}

Basic Usage

In TanStack Router, you can use createStandardSchemaV1 to integrate with route search parameter validation.

import { createFileRoute } from '@tanstack/react-router'
import { useQueryState, parseAsString, parseAsInteger, createStandardSchemaV1 } from 'nuqs'

const searchParams = {
  q: parseAsString.withDefault(''),
  page: parseAsInteger.withDefault(1)
}

export const Route = createFileRoute('/search')({
  validateSearch: createStandardSchemaV1(searchParams, { partialOutput: true }),
  component: SearchPage
})

function SearchPage() {
  const [query, setQuery] = useQueryState('q', parseAsString.withDefault(''))
  const [page, setPage] = useQueryState('page', parseAsInteger.withDefault(1))

  return (
    <div>
      <input value={query} onChange={(e) => setQuery(e.target.value)} />
      <p>Page: {page}</p>
    </div>
  )
}

TanStack Router support is being developed as a complementary feature that provides additional options alongside nuqs's core functionality.

Other Improvements ✨

In addition to the major features mentioned above, nuqs 2.5.0 includes many other improvements.

Const modifier for literal parsers

The parseAsStringLiteral now supports the const modifier, enabling more accurate type inference.

// Before
const statusParser = parseAsStringLiteral(['draft', 'published', 'archived'])
// Type: string

// 2.5.0 and later
const statusParser = parseAsStringLiteral(['draft', 'published', 'archived'] as const)
// Type: 'draft' | 'published' | 'archived'

const [status, setStatus] = useQueryState('status', statusParser)
// status type is inferred correctly

This improves the developer experience with more precise type inference.

Enhanced default options for NuqsAdapter

The NuqsAdapter now allows setting global default options.

import { NuqsAdapter } from 'nuqs/adapters/next/app'

export default function RootLayout({ children }) {
  return (
    <html>
      <body>
        <NuqsAdapter
          defaultOptions={{
            history: 'push',
            shallow: false,
            scroll: true,
            clearOnDefault: true
          }}
        >
          {children}
        </NuqsAdapter>
      </body>
    </html>
  )
}

This allows applying consistent options across the entire application.

Performance Optimizations

Bundle Size Optimization

nuqs 2.5.0 maintains zero runtime dependencies while reducing the bundle size to under 5.5KB.

nuqs@2.4.x: ~6.2KB (gzipped)
nuqs@2.5.0: ~5.4KB (gzipped) ⬇️ 13% reduction

Improved Tree Shaking

With improved tree shaking, unused features are now excluded from the bundle.

// Unused parsers are automatically excluded from the bundle
import { parseAsString, parseAsInteger } from 'nuqs'
// parseAsFloat, parseAsBoolean, etc. are not included

API Improvements

Introduction of defaultRateLimit

A defaultRateLimit has been added to disable custom rate limiting and revert to the default behavior.

import { debounce, defaultRateLimit } from 'nuqs'

const [search, setSearch] = useQueryState('q', {
  limitUrlUpdates: debounce(1000) // Normally a 1-second debounce
})

// Update immediately for a specific operation
const handleSubmit = () => {
  setSearch(value, {
    limitUrlUpdates: defaultRateLimit // Revert to default
  })
}

Improved Type Inference for urlKeys

The type inference for the urlKeys option has been improved, allowing for safer code.

import { type UrlKeys } from 'nuqs'

const parsers = {
  latitude: parseAsFloat.withDefault(35.6762),
  longitude: parseAsFloat.withDefault(139.6503)
}

// Type-safe urlKeys definition
const urlKeys: UrlKeys<typeof parsers> = {
  latitude: 'lat', // ✅ OK
  longitude: 'lng', // ✅ OK
  // invalidKey: 'invalid' // ❌ Compile error
}

Next.js 15.5 Typed Routes Support

Although not a feature added in nuqs 2.5 specifically, the official X account posted a createTypedLink() utility function for the typed routes feature introduced in Next.js 15.5. This function enables type-safe link generation.

https://x.com/nuqs47ng/status/1958643771643764893

These improvements make nuqs 2.5.0 a more stable, faster, and type-safe library.

Summary 📌

nuqs 2.5.0 is an update that significantly enhances the functionality of the URL state management library. With this release, developers can build more type-safe and performant web applications.

That's all!

Discussion