Usage
This is a basic guide on how to utilize sse-hooks in your React or Next.js projects. The library is designed to be plug-and-play, with consistent APIs across all hooks.
Importing Hooks
You can import any hook directly from the main package. All hooks are named exports to ensure tree-shaking works correctly, keeping your bundle size small.
import { useWindowSize, useLocalStorage } from 'sse-hooks'
##Hook Configuration Most hooks in this library accept an optional configuration object as their last argument. This allows you to customize behavior such as serialization, throttling, or initial states without breaking changes.
State Hooks
For hooks that persist data (like useLocalStorage or useSessionStorage), you can configure custom serializers or error handling.
const [value, setValue] = useLocalStorage('my-key', {
// Initial value
defaultValue: 'light',
// Custom serializer (optional)
serializer: (value) => JSON.stringify(value),
// Custom deserializer (optional)
deserializer: (value) => JSON.parse(value),
// Handle errors during storage access
onError: (error) => console.error('Storage error:', error)
})
Sensor Hooks
Sensors often allow you to configure the reference element or update timing. For example, useResizeObserver lets you define the box model.
const ref = useRef(null)
useResizeObserver(ref, (entry) => console.log(entry), {
// 'content-box' | 'border-box' | 'device-pixel-content-box'
box: 'border-box'
})
Network Hooks
The useFetch hook exposes a robust configuration object to handle caching, policies, and interceptors.
const { data } = useFetch('[https://api.example.com/data](https://api.example.com/data)', {
// 'cache-first' | 'network-only' | 'stale-while-revalidate'
cachePolicy: 'stale-while-revalidate',
// Automatically retry on failure
retries: 3,
// Custom headers
headers: {
'Authorization': 'Bearer token'
}
})