Overview
The useSessionStorage hook facilitates the synchronization of a React state with session storage, making it easy to persist state data across page reloads. This hook is particularly useful for scenarios where you need to maintain stateful data during a single browser session.
By incorporating useSessionStorage in your React components, you can efficiently manage state persistence across page reloads, enhancing the user experience and maintaining consistent application state.
Key Features
- State Persistence: Maintains state data across page reloads using session storage.
- Ease of Use: Provides a simple and intuitive API for state management with session storage.
- Custom Serialization: Supports both raw string storage and JSON serialization for storing complex data types.
How It Works
The hook takes a key, an initial value, and an optional boolean indicating whether to store the data as a raw string. It manages the state and automatically updates session storage whenever the state changes.
Syntax
const [value, setValue] = useSessionStorage(key, initialValue, raw);key: The key used for storing data in session storage.initialValue: The initial value for the state if not already in session storage.raw: If true, stores the value as a string without JSON serialization. Default value isfalse.
Usage Example
Here’s an example demonstrating the use of the useSessionStorage hook:
import { useState } from 'react';
import { useSessionStorage } from '@akinon/ui-hooks';
const MyComponent = () => {
const [sessionValue, setSessionValue] = useSessionStorage(
'myKey',
'Initial Value'
);
const updateSessionValue = () => {
setSessionValue('Updated Value');
};
return (
<div>
<p>Session Value: {sessionValue}</p>
<button onClick={updateSessionValue}>Update Value</button>
</div>
);
};
export default MyComponent;