Preferences
usePreferences hook, resolvePreferences, and related types
usePreferences
Manages user preferences for how measurements are displayed: unit view, standing charge visibility, tax inclusion, and chart vs table view. Optionally connects to a storage adapter.
Storage adapters such as localStorage and nuqs control the hook from their current snapshot during render. When no adapter is provided, the hook keeps local React state that resets on unmount.
import { usePreferences } from "@octopus-energy/measurements/preferences";usePreferencesProp
Type
import { usePreferences } from "@octopus-energy/measurements/preferences";
import { createLocalStorageAdapter } from "@octopus-energy/measurements/storage/local-storage";
const storage = createLocalStorageAdapter();
const [preferences, preferencesActions] = usePreferences({ storage });UsePreferencesOptionsProp
Type
Overrides
Use overrides when app data needs to constrain the user's preferences. The
function must be pure: return the original preferences when no constraint
applies, or return a new Preferences object with the enforced values.
The hook returns overridden preferences during render to avoid UI flicker, then commits the effective preferences back to local React state or storage after render. Actions that would violate the override are normalized in the same way.
const [preferences, preferencesActions] = usePreferences({
storage,
overrides: (preferences) => {
if (hasCostData) return preferences;
return { ...preferences, unit: "kWh" };
},
});resolvePreferences
Computes a complete Preferences object from optional inputs. Applies the same
defaults as usePreferences: unit = "kWh", standingCharge = true,
tax = true, and view = "chart". Useful for server-side resolution where
hooks cannot be called.
import { resolvePreferences } from "@octopus-energy/measurements/preferences";resolvePreferencesProp
Type
import { resolvePreferences } from "@octopus-energy/measurements/preferences";
const parsed = await searchParamsCache.parse(searchParams);
const preferences = resolvePreferences(parsed);ResolvePreferencesConfigProp
Type
createPreferencesActions
Creates a PreferencesActions object that writes preference inputs to a
StorageAdapter. Useful for controlled integrations where the current
preferences are resolved elsewhere, such as nuqs URL params parsed on the
server.
import { createPreferencesActions } from "@octopus-energy/measurements/preferences";createPreferencesActionsProp
Type
import {
createPreferencesActions,
resolvePreferences,
} from "@octopus-energy/measurements/preferences";
const preferences = resolvePreferences(searchParams);
const actions = createPreferencesActions(preferences, storage);Types
PreferencesProp
Type
PreferencesActionsProp
Type
| Type | Values |
|---|---|
UnitView | "kWh" | "cost" |
View | "chart" | "table" |