This module provides a custom React hook for managing state that is synchronized with URL search parameters in react-router@6-7 applications.
A custom React hook that manages state and synchronizes it with URL search parameters.
defaultState: object
- An object representing the default state values.replace?: boolean
- Control willsetUrl
usereplace
orpush
methods on router, default replace=true, can override byupdateUrl(stateObj, { replace: false })
options?: NavigateOptions
-replace
arg and types fromNavigateOptions
ofreact-router
type, same as options fromuseNavigate
useHistory
- Optionally can use window.history for navigationpreventScrollReset
- Option from react-router navigate
An object containing:
urlState: object
- The current state.setState: Function
- Function to update the state without updating the URL.setUrl: Function
- Function to update both the state and the URL.reset: Function
- Function to reset state to default.
import { useUrlState } from 'state-in-url/react-router';
const form = { name: '', age: 0 };
const { urlState, setState, setUrl } = useUrlState(form);
// Update state without changing URL
setState({ name: 'test' });
// options from type `NavigateOptions` from 'react-router`
setState(currVal => ({ ...currVal, name: 'test' }) );
// Update state and URL
setUrl({ name: 'test' }, { replace: false, preventScrollReset: false });
Updates the state without modifying the URL.
value: T | Partial<T> | T => T
- New state value or a function that receives the current state and returns the new state....NavigateOptions
- props from NavigateOptions ofreact-router
type, same as options fromuseNavigate
Updates both the state and the URL.
value?: T | Partial<T> | (currState: T) => T
- Optional new state value or a function that receives the current state and returns the new state.options?: NavigateOptions
- Optional options object from react-router'sNavigateOptions
type.
Updates both the state and the URL.
options?: NavigateOptions
- Optional options object from react-router'sNavigateOptions
type.