useCache

React hook for an in-memory key-value cache with TTL expiration, reactive callbacks, and type safety.

pnpm add react-callback-hooks

Demo

empty
Click a key to cache it — entries expire after 5s.

Usage

import { useCache } from 'react-callback-hooks'

const cache = useCache<string, User>({
  ttl: 5_000,
  onSet: (key, value) => console.log('set', key, value),
  onExpire: (key) => console.log('expired', key),
  onDelete: (key) => console.log('deleted', key)
})

cache.set('user:1', { name: 'David' })
cache.get('user:1') // User | undefined
cache.has('user:1') // boolean
cache.delete('user:1')
cache.clear()
cache.size // number
cache.entries // ReadonlyMap<K, V>

Shorthand — fires on set:

const cache = useCache<string, string>((key, value) => {
  console.log('cached', key, value)
})

Parameters

Shorthand form

ParameterTypeDescription
onSet(key: K, value: V) => voidOptional. Called whenever a value is set.

Object form

PropertyTypeDefaultDescription
ttlnumberundefinedTime in ms before an entry auto-expires.
onSet(key: K, value: V) => voidCalled when a value is written.
onExpire(key: K) => voidCalled when an entry expires after ttl ms.
onDelete(key: K) => voidCalled when delete() is called explicitly.

Return Values

PropertyTypeDescription
get(key)V | undefinedReturns the cached value or undefined.
set(key, value)voidStores a value, restarting its TTL timer if one exists.
delete(key)voidRemoves an entry and cancels its timer.
clear()voidRemoves all entries and cancels all timers.
has(key)booleanReturns true if the key exists.
sizenumberCurrent number of entries.
entriesReadonlyMap<K, V>Current snapshot of the store.