Skip to content

Instantly share code, notes, and snippets.

@zbeyens
Created August 29, 2024 13:39
Show Gist options
  • Save zbeyens/3cf7aa2211c09b70c132dc63e7d140be to your computer and use it in GitHub Desktop.
Save zbeyens/3cf7aa2211c09b70c132dc63e7d140be to your computer and use it in GitHub Desktop.

Using nuqs for URL Query State Management

nuqs is used for managing URL query state in Next.js applications. Follow these guidelines when working with it:

  1. Import necessary functions from nuqs:

    import { parseAsBoolean, parseAsStringEnum, useQueryState } from "nuqs";
  2. Create a custom hook for each query parameter:

    export const useMyParameterState = () => {
      return useQueryState(
        "parameterName",
        parseAsStringEnum(["option1", "option2"])
          .withDefault("option1")
          .withOptions({ history: "push" }),
      );
    };
  3. Use history push if you think the user will want to navigate back to the previous state:

    export const useBooleanState = () => {
      return useQueryState(
        "boolParam",
        parseAsBoolean.withDefault(false).withOptions({
          history: "push",
        }),
      );
    };
  4. Use the custom hooks in your components:

    const [value, setValue] = useMyParameterState();
  5. Update the URL query when changing values:

    void setValue("newValue");

Remember to define your query state hooks in a central location (e.g., useQueryState.ts) for easy reuse across your application.

Reference: apps/web/src/lib/navigation/useQueryState.ts

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment