Skip to content

Subscription API

All methods below are available on both ReactiveResponsiveState and ContainerState.

subscribe(listener) → unsubscribe

Fires immediately with the current state, then on every change. Affected by debounce.

ts
const stop = state.subscribe((s) => {
  document.body.dataset.bp = Object.keys(s)
    .filter((k) => s[k])
    .join(' ')
})
stop() // unsubscribe

on(key, callback) → unsubscribe

Fires immediately with the current value for key, then on every change. Never debounced.

ts
const off = state.on('mobile', (matches) => {
  header.classList.toggle('header--mobile', matches)
})
off()

onEnter(key, callback) → unsubscribe

Fires only on false → true transitions. Skips the initial value. Never debounced.

ts
state.onEnter('mobile', () => initMobileMenu())

onLeave(key, callback) → unsubscribe

Fires only on true → false transitions. Skips the initial value. Never debounced.

ts
state.onLeave('mobile', () => destroyMobileMenu())

once(key, callback) → unsubscribe

Fires on the next change to key, then auto-unsubscribes. Does not fire for the current value. Never debounced.

ts
state.once('mobile', (matches) => {
  console.log('mobile changed to:', matches)
})

onNextChange(callback) → unsubscribe

Fires on the next global state change, then auto-unsubscribes. Affected by debounce.

ts
state.onNextChange((s) => console.log('first change:', s))

onBreakpointChange(callback) → unsubscribe

Fires when the active breakpoint changes (i.e. current changes), providing from and to. Affected by debounce.

ts
state.onBreakpointChange((from, to) => {
  console.log(`breakpoint: ${from} → ${to}`)
})

waitFor(key, expectedValue?) → Promise

Returns a Promise that resolves when key reaches expectedValue (default true). Resolves immediately if already met. Never debounced.

ts
await state.waitFor('desktop')
initDesktopChart()

// Wait for mobile to become false
await state.waitFor('mobile', false)

Ordered breakpoint helpers

These helpers require a breakpoint order — either set via setConfig / createResponsiveState options, or derived from config key insertion order.

state.current: getter

Returns the first active breakpoint key in order, or null.

ts
if (state.current === 'mobile') showDrawer()

state.isAbove(key) → boolean

true when the current breakpoint comes after key in the order.

ts
// order: ['xs', 'sm', 'md', 'lg', 'xl']
// current = 'lg'
state.isAbove('sm') // → true
state.isAbove('xl') // → false

state.isBelow(key) → boolean

true when the current breakpoint comes before key in the order.

ts
state.isBelow('md') // → true  (current = 'sm')

state.between(from, to) → boolean

true when the current breakpoint is between from and to (inclusive).

ts
state.between('sm', 'lg') // → true  (current = 'md')