Skip to content

Subscription API ​

All methods below are available on both ReactiveResponsiveState and ContainerState. Unless noted otherwise, each returns an unsubscribe function (() => void).

Subscribe ​

subscribe(listener)

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

Listen to a Key ​

on(key, callback)

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()

On Enter ​

onEnter(key, callback)

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

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

On Leave ​

onLeave(key, callback)

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

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

Once ​

once(key, callback)

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)
})

On Next Change ​

onNextChange(callback)

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

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

On Breakpoint Change ​

onBreakpointChange(callback)

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}`)
})

Wait For ​

waitFor(key, expectedValue?)

Promise<void>

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 ​

string | null

Getter. 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')