Core & storage
The store has no React in it. Import it from input-cooldown/core to use it with any framework, or plug in your own storage.
createCooldownStore()
Same options as useCooldown(). Exposes the useSyncExternalStore contract.
import { createCooldownStore } from 'input-cooldown/core'
const store = createCooldownStore({ storageKey: 'otp', duration: 30, onResend: send })
const unsubscribe = store.subscribe(() => {
const { status, remaining, canResend } = store.getSnapshot()
button.textContent = status === 'counting' ? `Resend in ${remaining}s` : 'Resend'
button.ariaDisabled = String(!canResend)
})
button.onclick = () => store.trigger()Timers and listeners only run while there is at least one subscriber. Unsubscribe everything and the store goes idle.
Storage adapters
| Prop | Type | Default |
|---|---|---|
createLocalStorage(prefix?)The default. Falls back to memory when localStorage throws. | StorageAdapter | 'input-cooldown:' |
createMemoryStorage()Per page only. Good for tests and demos. | StorageAdapter | — |
Custom adapter
Implement get, set, remove and optionally subscribe. Here is one that uses sessionStorage, so the state is per tab:
import type { StorageAdapter } from 'input-cooldown/core'
export const sessionAdapter: StorageAdapter = {
get: key => {
try {
return JSON.parse(sessionStorage.getItem(key) ?? 'null')
} catch {
return null
}
},
set: (key, value) => sessionStorage.setItem(key, JSON.stringify(value)),
remove: key => sessionStorage.removeItem(key),
}Pass the same adapter instance on every render (define it at module level). A new adapter means a new store.
Helpers
| Prop | Type | Default |
|---|---|---|
formatRemaining(s)75 → "1:15". | string | — |
durationFor(duration, attempt)Seconds for a given attempt of a backoff schedule. | number | — |
remainingMs(state, now)Milliseconds left, clamped against clock changes. | number | — |