Skip to content

Hooks ​

The library exposes its state as React hooks — call one in a component and it returns the current value and re-renders whenever that value changes.

They keep your in-app UI in sync with playback, the queue, the browse tree, and the device, including changes driven from outside your app (the lock screen, CarPlay, Android Auto, Bluetooth).

tsx
import { useActiveTrack, usePlayingState } from 'react-native-audio-browser'

function NowPlaying() {
  const track = useActiveTrack()
  const { playing } = usePlayingState()
  return (
    <Text>
      {playing ? 'Playing' : 'Paused'}: {track?.title}
    </Text>
  )
}

The getter / hook / event trio ​

Most state comes in three forms, so you can read it whichever way fits:

FormShapeUse it
HookuseX()inside a component — re-renders on change
GettergetX()a one-off synchronous read, anywhere
Eventon…onX.addListener(cb) outside React — returns an unsubscribe

Most events are named on<Thing>Changed, but several aren't — onProgressUpdated, onPlayingState, onPlaybackError, onNavigationError. The exact event for each hook is in the reference table, so don't guess the name.

ts
import { getPlayback, onPlaybackChanged } from 'react-native-audio-browser'

const now = getPlayback() // read once
// subscribe
const stop = onPlaybackChanged.addListener((p) => console.log(p.state))
// stop() to unsubscribe

Every hook, getter, and event is a named export from react-native-audio-browser. Hooks read a cached value synchronously on first render (no flash of empty state) and then subscribe for you, except usePolledProgress, which starts at zero and fills in on its first poll.

Mutating state is separate — setX() / action functions (play, setQueue, setShuffle, setRepeatMode, setPlayWhenReady, …) — covered in Basic Usage.

Playback ​

The transport state — what the player is doing right now.

tsx
import {
  usePlayback,
  usePlayingState,
  useProgress
} from 'react-native-audio-browser'

function Transport() {
  const { state } = usePlayback() // e.g. 'playing' | 'paused' (full list below)
  const { playing, buffering } = usePlayingState()
  const { position, duration, buffered } = useProgress() // seconds
  return <Scrubber position={position} duration={duration} />
}
  • usePlayback() → { state, error? }. state is one of none, ready, loading, buffering, playing, paused, stopped, ended, error.
  • usePlayingState() → { playing, buffering }. A lighter hook when you only need the booleans.
  • useProgress() → Progress ({ position, duration, buffered }) in seconds. Event-driven, but off by default: progressUpdateEventInterval is null until you set it (in seconds) in setupPlayer or updateOptions, e.g. progressUpdateEventInterval: 0.5 — otherwise the value never ticks.
  • usePolledProgress(updateInterval = 1000) → same Progress, but polled on its own timer (milliseconds) instead of event-driven, so it works without progressUpdateEventInterval. Good for a smooth scrubber; it pauses while the app is backgrounded.
  • usePlayWhenReady() → boolean: whether the player will start as soon as content is ready.
  • useSystemVolume() → number 0–1, the device volume (read-only on iOS).

useProgress vs usePolledProgress

useProgress emits at the global progressUpdateEventInterval (and stays still until you set it); usePolledProgress ignores that and ticks on its own timer. For a scrubber, usePolledProgress is usually the simpler choice.

Queue and active track ​

tsx
import {
  getTrackIdentity,
  useActiveTrack,
  useQueue,
  useRepeatMode,
  useShuffle
} from 'react-native-audio-browser'

function QueueScreen() {
  const active = useActiveTrack() // Track | undefined
  const queue = useQueue() // Track[]
  const repeat = useRepeatMode() // 'off' | 'track' | 'queue'
  const shuffle = useShuffle() // boolean
  return <List data={queue} highlight={active && getTrackIdentity(active)} />
}

useActiveTrack updates even when the track changes from an external control (car next/previous), so matching on the track's identity keeps your UI correct. Compare tracks by identity: id when set, else src. getTrackIdentity(track) gives you the same comparison the library uses (see Track).

Now playing ​

useNowPlaying() → NowPlayingMetadata | undefined — the metadata shown on the lock screen and car surfaces.

On iOS and Android it returns what those surfaces show, in priority order: a flashNowPlaying() flash first, then your nowPlaying formatter, then any override you set via updateNowPlaying() (e.g. the current song on a live stream), then the active track's own fields. On web there is no formatter, and a flash replaces your override (see the flash). See the four metadata layers.

tsx
const meta = useNowPlaying()
// { title?, artist?, album?, artwork?, genre?, duration?,
//   description?, mediaId?, elapsedTime? (iOS only, not live) }

useTimedMetadata() → TimedMetadata | undefined — the stream's current song (ICY or ID3), cleared on a track change until the next one arrives. Always undefined on web.

Browsing ​

Mirror the browse tree your app draws — the same state CarPlay and Android Auto render.

  • useTabs() → Track[] | undefined — the top-level tabs.
  • usePath() → string | undefined — the current browse path.
  • useContent() → ResolvedTrack | undefined — the resolved page (content?.sections to render — each a titled, styled group of tracks).
tsx
import { useContent, navigate } from 'react-native-audio-browser'

function Browse() {
  const page = useContent()
  // each section: { title?, style?, path?, children: Track[] }
  return (
    <List
      sections={page?.sections ?? []}
      onSelect={(track) => navigate(track)}
    />
  )
}

See Browser for how navigation and content resolution work.

Sleep timer ​

  • useSleepTimerActive() → boolean — lightweight "is a timer set?" check.
  • useSleepTimer(params?) → the live SleepTimerState, or undefined when none is set:
    • { time, secondsLeft } for a countdown timer (time is the epoch-ms fire time), or
    • { sleepWhenPlayedToEnd: true } for an end-of-track timer.
tsx
const timer = useSleepTimer({ updateInterval: 1000 })
// timer && 'secondsLeft' in timer → show timer.secondsLeft

params takes updateInterval (countdown tick rate, default 1000ms) and inactive (set true while backgrounded to pause ticking). secondsLeft does not advance in the background.

Device and environment ​

HookReturnsNotes
useOnline()booleannetwork connectivity
useCarConnected()booleanCarPlay / Android Auto connected (false on web)
useSystemVolume()numberdevice volume 0–1
useOutput()Output | undefinedcurrent audio output (iOS + Android)
tsx
const output = useOutput() // { type, name, external } | undefined
// e.g. output?.type === 'bluetooth', output?.external === true

useOutput updates as routes change (AirPods connect, a Bluetooth speaker is selected, etc.); it's undefined when unknown. On Android below 13 (API 33) it can miss a reroute made while a device stays connected; see The current output.

Errors ​

  • usePlaybackError() → PlaybackError | undefined — playback failures, with a normalized kind (offline, unreachable, not-found, rejected, unplayable, stalled, …) to branch on, plus a platform-specific code and optional statusCode for telemetry. Never show its message — see Errors. Terminal errors only: an error the player is still retrying (retrying: true) arrives on usePlayback().error — see Errors while retrying.
  • useNavigationError() → NavigationError | undefined — a browse/search failure, with a typed code (network-error, http-error, timeout, empty-content, …) and optional statusCode.
  • useFormattedNavigationError() → FormattedNavigationError | undefined ({ title, message? }) — the same error run through your formatNavigationError config (the copy CarPlay and Android Auto show), ready to display.
tsx
const error = useFormattedNavigationError()
return error ? <Banner title={error.title} body={error.message ?? ''} /> : null

Player options ​

useOptions() → the current Options (jump intervals, capabilities, and the android / ios blocks). Mutate with updateOptions(partial).

tsx
const { forwardJumpInterval, capabilities } = useOptions()

Android-only hooks ​

Battery (Android background-restriction state — all false/unrestricted on iOS):

tsx
const { pending, status, dismiss, openSettings } = useBatteryWarning()

Equalizer: useEqualizerSettings() → EqualizerSettings | undefined (bandLevels, presets, enabled, …); undefined on iOS. Drive it with setEqualizerEnabled / setEqualizerPreset / setEqualizerLevels.

Debugging ​

useDebug(options?) → { state, logs, clear } — a live snapshot of the core player state (playback, queue, options, browse path, errors) plus a bounded log of recent changes. It's a development aid; options.enabled defaults to __DEV__.

tsx
const { state, logs, clear } = useDebug({ metadata: true })

All hooks at a glance ​

The Event column is the emitter for the getter/event form, the Hook name links to its full API entry, and the Returns type links to its definition where it has one.

HookReturnsEventPlatform
usePlayback{ state, error? }onPlaybackChangedall
usePlayingState{ playing, buffering }onPlayingStateall
useProgress{ position, duration, buffered }onProgressUpdatedall
usePolledProgress{ position, duration, buffered }(polled)all
usePlayWhenReadybooleanonPlayWhenReadyChangedall
useSystemVolumenumberonSystemVolumeChangedall (read-only iOS)
useActiveTrackTrack | undefinedonActiveTrackChangedall
useQueueTrack[]onQueueChangedall
useRepeatModeRepeatModeonRepeatModeChangedall
useShufflebooleanonShuffleChangedall
useNowPlayingNowPlayingMetadata | undefinedonNowPlayingChangedall
useTimedMetadataTimedMetadata | undefinedonTimedMetadataiOS, Android
useTabsTrack[] | undefinedonTabsChangedall
usePathstring | undefinedonPathChangedall
useContentResolvedTrack | undefinedonContentChangedall
useSleepTimerActivebooleanonSleepTimerChangedall
useSleepTimerSleepTimerState | undefinedonSleepTimerChangedall
useOnlinebooleanonOnlineChangedall
useCarConnectedbooleanonCarConnectedChangedall (false web)
useOutputOutput | undefinedonOutputChangediOS, Android
usePlaybackErrorPlaybackError | undefinedonPlaybackErrorall
useNavigationErrorNavigationError | undefinedonNavigationErrorall
useFormattedNavigationErrorFormattedNavigationError | undefinedonFormattedNavigationErrorall
useOptionsOptionsonOptionsChangedall
useBatteryWarning{ pending, status, dismiss, openSettings }(composite)Android
useBatteryWarningPendingbooleanonBatteryWarningPendingChangedAndroid
useBatteryOptimizationStatusBatteryOptimizationStatusonBatteryOptimizationStatusChangedAndroid
useEqualizerSettingsEqualizerSettings | undefinedonEqualizerChangedAndroid
useDebug{ state, logs, clear }(composite)all

For the exact return types, see the API reference.