use-hash-params
v0.1.0
Published
React hook to sync state with URL hash parameters
Maintainers
Readme
use-hash-params
React hook to sync state with URL hash parameters. State updates when the URL changes and the URL changes when state updates — without infinite loops.
Install
npm install use-hash-paramsUsage
import { useHashParams } from "use-hash-params";
function App() {
const [state, setState] = useHashParams({
page: 1,
search: "",
active: false,
});
return (
<div>
<p>Page: {state.page}</p>
<input
value={state.search}
onChange={(e) => setState({ search: e.target.value })}
/>
<button onClick={() => setState((prev) => ({ page: prev.page + 1 }))}>
Next page
</button>
</div>
);
}The URL hash reflects the state: #page=2&search=hello. Default values are omitted from the hash to keep URLs clean.
Types are inferred from the defaults — page is number, search is string, active is boolean.
Options
const [state, setState] = useHashParams(
{ page: 1 },
{ pushHistory: false },
);| Option | Type | Default | Description |
|---|---|---|---|
| pushHistory | boolean | true | When true, state changes push new history entries, enabling browser back/forward navigation. When false, state changes replace the current entry. |
API
setState(update)
Accepts a partial state object or an updater function:
// Partial object
setState({ page: 2 });
// Updater function
setState((prev) => ({ page: prev.page + 1 }));Supported value types
string— URI-encoded in the hashnumber— parsed withNumber(), falls back to default ifNaNboolean— serialized astrue/false
License
MIT
