- 🌟 Overview
- 🚀 Features
- 📚 Installation
- ✨ Demo
- 🛠️ API
- 🔧 Usage Examples
- 📝 Notes
- 📦 useStorage Hook
- 📜 License
- 🎉 Acknowledgments
useUrlStorageState
is a hook designed to synchronize state between URL parameters and browser storage (e.g., localStorage
or sessionStorage
). This hook helps you maintain consistent state across page refreshes, multiple tabs, and deep links while allowing for custom configurations.
- Bidirectional Sync: Synchronizes state between URL parameters and browser storage seamlessly.
- Persistence: Retains state across page refreshes.
- Type Safety: Fully generic for strongly-typed state.
- Customizable: Supports custom storage, key prefixing, and serialization methods.
- Multi-State Management: Easily handles multiple independent states.
Install the package via npm or yarn:
npm install use-url-storage-state
Ensure that react
and react-router-dom
are installed in your project
import React from 'react';
import { useUrlStorageState } from 'use-url-storage-state';
const Demo = () => {
const [filters, setFilters] = useUrlStorageState({
key: 'filters',
defaultValue: { search: '', category: 'all' },
});
return (
<div>
<input
type='text'
value={filters.search}
onChange={(e) => setFilters({ ...filters, search: e.target.value })}
/>
<select
value={filters.category}
onChange={(e) => setFilters({ ...filters, category: e.target.value })}
>
<option value='all'>All</option>
<option value='electronics'>Electronics</option>
<option value='fashion'>Fashion</option>
</select>
</div>
);
};
export default Demo;
type useUrlStorageStateParams<T> = {
key: string; // URL parameter and storage key
defaultValue: T; // Default value if none exists
prefix?: string; // Optional storage key prefix (default: current pathname)
storage?: Storage; // Optional storage type (default: localStorage)
};
[T, (newValue: T) => void]
-
T
: The current state value. -
(newValue: T) => void
: A function to update the state.
import { useUrlStorageState } from 'use-url-storage-state';
const [filters, setFilters] = useUrlStorageState({
key: 'filters',
defaultValue: { search: '', category: 'all' },
});
// URL: http://localhost:3000/?filters={"search":"","category":"all"}
// Storage: urlStorage_/current_pathname_filters
Using a shared prefix is useful when you want states across different paths or to share the same logical grouping in storage. For example, you might want all multiple pages to affect and persist the same url params:
import { useUrlStorageState } from '@your-library/use-url-storage-state';
const [filters, setFilters] = useUrlStorageState({
key: 'filters',
defaultValue: { search: '', category: 'all' },
prefix: 'somePrefix',
});
// URL: http://localhost:3000/?filters={"search":"","category":"all"}
// Storage: somePrefix_filters
By default, the prefix is set to the current location.pathname
. This ensures that states are unique to each page in your application. For instance, if you navigate from /home
to /profile
, the storage keys will differ:
-
/home
:urlStorage_/home_filters
-
/profile
:urlStorage_/profile_filters
This behavior prevents cross-page conflicts and keeps the state isolated to its corresponding route.
import { useUrlStorageState } from '@your-library/use-url-storage-state';
const [sessionState, setSessionState] = useUrlStorageState({
key: 'userSession',
defaultValue: { loggedIn: false },
storage: sessionStorage,
});
import { useUrlStorageState } from '@your-library/use-url-storage-state';
const [filters, setFilters] = useUrlStorageState({
key: 'filters',
defaultValue: { search: '', category: 'all' },
});
const [theme, setTheme] = useUrlStorageState({
key: 'theme',
defaultValue: { darkMode: false },
});
- URL parameters are always strings, so complex objects are automatically serialized/deserialized
- The hook maintains sync between URL and storage.
- If a URL parameter exists, it will update the storage
- If a storage value exists, and no URL parameter exists, it will update the URL
- If none exists, it will populate the URL and storage with the default value
- The default state will populate the URL and storage if none exists automatically
- The hook will only refer to queryParams that exists in state, and will ignore any other query params
The useStorage
hook is a low-level utility for interacting with browser storage (e.g., localStorage
, sessionStorage
). It provides reactive state management tied to storage keys, making it easy to persist and retrieve data.
- Custom Serialization: Allows for custom serialization and deserialization of storage values.
- Live Synchronization: Keeps state synchronized across tabs.
- Default Value Initialization: Initializes storage keys with default values.
type StorageProps<ValueType> = {
key: string; // The storage key.
defaultValue: ValueType; // Default value if no value exists.
storage?: Storage; // Storage type (localStorage/sessionStorage). Default: localStorage.
live?: boolean; // Synchronize across tabs. Default: false.
serialize?: (value: ValueType) => string; // Custom serialization function. Default: JSON.stringify.
deserialize?: (str: string) => ValueType; // Custom deserialization function. Default: JSON.parse.
forceInit?: (value?: string) => boolean; // Force initialization logic. Default: never.
};
[ValueType, (newValue: ValueType) => void]
import { useStorage } from '@your-library/use-url-storage-state';
const [value, setValue] = useStorage({
key: 'myKey',
defaultValue: 'defaultValue',
});
setValue('newValue');
import { useStorage } from '@your-library/use-url-storage-state';
const [user, setUser] = useStorage({
key: 'user',
defaultValue: { name: 'Guest' },
serialize: (value) => btoa(JSON.stringify(value)),
deserialize: (str) => JSON.parse(atob(str)),
});
import { useStorage } from '@your-library/use-url-storage-state';
const [theme, setTheme] = useStorage({
key: 'theme',
defaultValue: 'light',
live: true,
});
import { useStorage } from '@your-library/use-url-storage-state';
const [count, setCount] = useStorage({
key: 'counter',
defaultValue: 0,
forceInit: (existingValue) =>
existingValue === undefined || existingValue === null,
});
// The key will be initialized to 0 only if it doesn't exist or is null.
setCount((prev) => prev + 1);
import { useStorage } from '@your-library/use-url-storage-state';
const [sessionData, setSessionData] = useStorage({
key: 'sessionKey',
defaultValue: 'sessionValue',
storage: sessionStorage,
});
setSessionData('newSessionValue');
-
Storage Type: The default storage is
localStorage
. If you need ephemeral data that clears on browser close, usesessionStorage
by setting thestorage
option. -
Custom Serialization: Use
serialize
anddeserialize
when working with complex objects, or when you need encrypted or encoded storage. -
Live Synchronization: Enable the
live
option for use cases that require real-time updates across browser tabs or windows, like theme synchronization or shared state. -
Force Initialization: The
forceInit
function is useful for cases where existing values might be invalid or require resetting.
This project is licensed under the MIT License
- Inspired by Kent C. Dodds, https://www.youtube.com/watch?v=yu3dnHrnps4
- Special thanks to Idan Entin