Implementation:Apache Druid UseHashAndLocalStorageHybridState
| Knowledge Sources | |
|---|---|
| Domains | Web_Console, State_Management |
| Last Updated | 2026-02-10 10:00 GMT |
Overview
useHashAndLocalStorageHybridState is a custom React hook that persists state in both the URL hash and localStorage, enabling shareable URLs and persistent browser state simultaneously.
Description
The hook initializes state by first attempting to decode the value from the URL hash fragment (base64-URL encoded with a given prefix), falling back to the value stored in localStorage under the given key, and finally using the provided initial value. When the state is updated, the hook pushes the new value into the browser history via the URL hash and simultaneously persists it to localStorage. It also listens for the browser's "popstate" event to synchronize state when the user navigates with back/forward buttons.
Usage
Used in the Druid web console workbench to persist query tab state, ensuring that SQL queries and tab configurations survive page reloads and can be shared via URL.
Code Reference
Source Location
- Repository: Apache Druid
- File: web-console/src/hooks/use-hash-and-local-storage-hybrid-state.ts
- Lines: 1-77
Signature
export function useHashAndLocalStorageHybridState<T>(
prefix: string,
key: LocalStorageKeys,
initialValue?: T,
inflateFn?: (x: any) => T,
): [T, Dispatch<SetStateAction<T>>];
Import
import { useHashAndLocalStorageHybridState } from './hooks/use-hash-and-local-storage-hybrid-state';
I/O Contract
Inputs
| Name | Type | Required | Description |
|---|---|---|---|
| prefix | string | Yes | A string prefix prepended to the base64-encoded hash value for namespace isolation |
| key | LocalStorageKeys | Yes | The localStorage key under which to persist the state |
| initialValue | T | No | The default value used when neither hash nor localStorage contains state |
| inflateFn | (x: any) => T | No | An optional deserialization function applied to raw values from hash or localStorage |
Outputs
| Name | Type | Description |
|---|---|---|
| state | T | The current state value |
| setState | Dispatch<SetStateAction<T>> | A setter function that updates state, URL hash, and localStorage simultaneously |
Usage Examples
Persisting workbench tab state
const [tabState, setTabState] = useHashAndLocalStorageHybridState<WorkbenchTabState>(
'#query/',
LocalStorageKeys.WORKBENCH_STATE,
defaultTabState,
raw => WorkbenchTabState.inflate(raw),
);