nuqs
is used for managing URL query state in Next.js applications. Follow these guidelines when working with it:
-
Import necessary functions from
nuqs
:import { parseAsBoolean, parseAsStringEnum, useQueryState } from 'nuqs';
-
Create a custom hook for each query parameter:
export const useMyParameterState = () => { return useQueryState( 'parameterName', parseAsStringEnum(['option1', 'option2']) .withDefault('option1') .withOptions({ history: 'push' }) ); };
-
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', }) ); };
-
Use the custom hooks in your components:
const [value, setValue] = useMyParameterState();
-
Update the URL query when changing values:
void setValue('newValue');
-
Use
clearOnDefault
option to remove the parameter from the URL when it's set to its default value:export const useConfigurationItemsState = () => { return useQueryState( 'configItems', parseAsJson<Record<string, string>>().withDefault({}).withOptions({ clearOnDefault: true, history: 'push', }) ); };
This ensures that empty or default values are not included in the URL search params, keeping the URL clean and only including relevant information.
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