0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【Next.js】nuqsを導入する方法

Posted at

nuqsとは

nuqsは状態をクエリパラメータで管理するためのライブラリです。

インストール

Yarnを使用している場合、以下のコマンドを実行してインストールします。

yarn add nuqs

アダプタ

Next.jsのApp Routerを使用する場合にはRootLayout{children}NuqsAdapterコンポーネントでラップします。

import { NuqsAdapter } from 'nuqs/adapters/next/app'
import { type ReactNode } from 'react'
 
export default function RootLayout({
  children
}: {
  children: ReactNode
}) {
  return (
    <html>
      <body>
        <NuqsAdapter>{children}</NuqsAdapter>
      </body>
    </html>
  )
}

使い方

以下のように記述することでカウントをクエリパラメータで管理できるようになります。

"use client"

import { useQueryState } from "nuqs"

export function Demo() {
  const [count, setCount] = useQueryState(
    "count",
    parseAsInteger.withDefault(0),
  )
  return (
		<button onClick={() => setCount((c) => c + 1)}>Count: {count}</button>
  )
}

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?