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).
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:
| Form | Shape | Use it |
|---|---|---|
| Hook | useX() | inside a component — re-renders on change |
| Getter | getX() | a one-off synchronous read, anywhere |
| Event | on… | 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.
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 unsubscribeEvery 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.
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? }.stateis one ofnone,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:progressUpdateEventIntervalisnulluntil you set it (in seconds) insetupPlayerorupdateOptions, e.g.progressUpdateEventInterval: 0.5— otherwise the value never ticks.usePolledProgress(updateInterval = 1000)→ sameProgress, but polled on its own timer (milliseconds) instead of event-driven, so it works withoutprogressUpdateEventInterval. 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()→number0–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
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.
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?.sectionsto render — each a titled, styled group of tracks).
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 liveSleepTimerState, orundefinedwhen none is set:{ time, secondsLeft }for a countdown timer (timeis the epoch-ms fire time), or{ sleepWhenPlayedToEnd: true }for an end-of-track timer.
const timer = useSleepTimer({ updateInterval: 1000 })
// timer && 'secondsLeft' in timer → show timer.secondsLeftparams 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
| Hook | Returns | Notes |
|---|---|---|
useOnline() | boolean | network connectivity |
useCarConnected() | boolean | CarPlay / Android Auto connected (false on web) |
useSystemVolume() | number | device volume 0–1 |
useOutput() | Output | undefined | current audio output (iOS + Android) |
const output = useOutput() // { type, name, external } | undefined
// e.g. output?.type === 'bluetooth', output?.external === trueuseOutput 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 normalizedkind(offline,unreachable,not-found,rejected,unplayable,stalled, …) to branch on, plus a platform-specificcodeand optionalstatusCodefor telemetry. Never show itsmessage— see Errors. Terminal errors only: an error the player is still retrying (retrying: true) arrives onusePlayback().error— see Errors while retrying.useNavigationError()→NavigationError| undefined— a browse/search failure, with a typedcode(network-error,http-error,timeout,empty-content, …) and optionalstatusCode.useFormattedNavigationError()→FormattedNavigationError| undefined({ title, message? }) — the same error run through yourformatNavigationErrorconfig (the copy CarPlay and Android Auto show), ready to display.
const error = useFormattedNavigationError()
return error ? <Banner title={error.title} body={error.message ?? ''} /> : nullPlayer options
useOptions() → the current Options (jump intervals, capabilities, and the android / ios blocks). Mutate with updateOptions(partial).
const { forwardJumpInterval, capabilities } = useOptions()Android-only hooks
Battery (Android background-restriction state — all false/unrestricted on iOS):
useBatteryWarning()→{ pending, status, dismiss, openSettings }— the meta-hook for a complete warning UI;dismiss()andopenSettings()are ready-to-wire actions.useBatteryWarningPending()→booleananduseBatteryOptimizationStatus()→'unrestricted' | 'optimized' | 'restricted'are the individual pieces.
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__.
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.
| Hook | Returns | Event | Platform |
|---|---|---|---|
usePlayback | { state, error? } | onPlaybackChanged | all |
usePlayingState | { playing, buffering } | onPlayingState | all |
useProgress | { position, duration, buffered } | onProgressUpdated | all |
usePolledProgress | { position, duration, buffered } | (polled) | all |
usePlayWhenReady | boolean | onPlayWhenReadyChanged | all |
useSystemVolume | number | onSystemVolumeChanged | all (read-only iOS) |
useActiveTrack | Track | undefined | onActiveTrackChanged | all |
useQueue | Track[] | onQueueChanged | all |
useRepeatMode | RepeatMode | onRepeatModeChanged | all |
useShuffle | boolean | onShuffleChanged | all |
useNowPlaying | NowPlayingMetadata | undefined | onNowPlayingChanged | all |
useTimedMetadata | TimedMetadata | undefined | onTimedMetadata | iOS, Android |
useTabs | Track[] | undefined | onTabsChanged | all |
usePath | string | undefined | onPathChanged | all |
useContent | ResolvedTrack | undefined | onContentChanged | all |
useSleepTimerActive | boolean | onSleepTimerChanged | all |
useSleepTimer | SleepTimerState | undefined | onSleepTimerChanged | all |
useOnline | boolean | onOnlineChanged | all |
useCarConnected | boolean | onCarConnectedChanged | all (false web) |
useOutput | Output | undefined | onOutputChanged | iOS, Android |
usePlaybackError | PlaybackError | undefined | onPlaybackError | all |
useNavigationError | NavigationError | undefined | onNavigationError | all |
useFormattedNavigationError | FormattedNavigationError | undefined | onFormattedNavigationError | all |
useOptions | Options | onOptionsChanged | all |
useBatteryWarning | { pending, status, dismiss, openSettings } | (composite) | Android |
useBatteryWarningPending | boolean | onBatteryWarningPendingChanged | Android |
useBatteryOptimizationStatus | BatteryOptimizationStatus | onBatteryOptimizationStatusChanged | Android |
useEqualizerSettings | EqualizerSettings | undefined | onEqualizerChanged | Android |
useDebug | { state, logs, clear } | (composite) | all |
For the exact return types, see the API reference.