API Reference
onReStateChange
Use onReStateChange for persistence, analytics, integrations, or another side effect that should run outside a React
render.
import { createReStateMethods, onReStateChange } from '@raulpesilva/re-state';
const { getTheme, dispatchTheme } = createReStateMethods<'theme', 'light' | 'dark'>('theme', 'light');
const unsubscribe = onReStateChange(() => {
localStorage.setItem('theme', getTheme());
}, ['theme']);
dispatchTheme('dark');
unsubscribe();The callback receives no arguments. Read the latest value with a getter, as the example does.
Keep in mind
- The callback does not run when you create the subscription.
- Every write or reset notification for a listed key runs the callback, even when the old and new values are equal.
- List each key once. A duplicate key creates a duplicate subscription.
- Cleanup is manual. Keep the returned unsubscribe function and call it when the listener is no longer needed.
Inside a component, subscribe from an effect and return the cleanup function:
useEffect(() => {
return onReStateChange(() => {
console.log(getConnection());
}, ['connection']);
}, []);Do not register a subscription during render.
API
function onReStateChange(callback: () => void, dependencies: string[]): () => void;| Parameter | Description |
|---|---|
callback | Function called after a listed key is written or reset |
dependencies | Keys to watch |
Unknown keys may be watched before they are initialized. Calling the returned unsubscribe function more than once is safe.
Use createGetReState to create the getters used inside a callback.