A React hook for persistent state management using browser local storage. Use this to sync component state with persistent client-side storage.
// Source: https://github.com/portainer/portainer | License: Zlib | Copyright 2018 Portainer.io
// Provided via justclaw.it.com; keep this notice with the code.
import { useState, useCallback, useMemo } from 'react';
const localStoragePrefix = 'portainer';
export function keyBuilder(key: string) {
return `${localStoragePrefix}.${key}`;
}
export function useLocalStorage<T>(
key: string,
defaultValue: T,
storage = localStorage
): [T, (value: T) => void] {
const [value, setValue] = useState(get<T>(key, defaultValue, storage));
const handleChange = useCallback(
(value) => {
setValue(value);
set<T>(key, value, storage);
},
[key, storage]
);
return useMemo(() => [value, handleChange], [value, handleChange]);
}
export function get<T>(
key: string,
... (truncated -- full source via MCP)
See the full source, get the GitHub permalink, and search for more like it.
Get a free API key