Keeping music playing across React routes with Redux Toolkit
Moving audio to the root of a Zing MP3 clone so routes can't stop it, then restoring the play position after a reload and splitting a hot selector.

In a Zing MP3 clone I built to learn React (Create React App, React 18, React Router 6, Redux Toolkit), opening the full-screen mobile player stopped the song. The <audio> element was rendered inside the desktop control bar, the mobile view unmounted that component, and the music went with it. The fix was to move audio to the root and let Redux and localStorage remember the track, the queue and the position.
Render the audio element outside anything that can unmount
The first version kept <audio> in Controls and passed a useRef down to ControlsCenter and ControlsRight as props. The full-screen ControlMobile player took the place of Controls at the same spot in the tree, so opening it unmounted the audio element too.
In the same change that added the mobile player, I moved the audio element up to the root, above the router:
// index.js
root.render(
<Provider store={store}>
<GlobalStyle>
<AudioProvider>
<App />
</AudioProvider>
</GlobalStyle>
</Provider>,
);
// AudioProvider.js
export const AudioContext = createContext();
const AudioProvider = ({ children }) => {
const audioRef = useRef(null);
return (
<AudioContext.Provider value={{ audioRef }}>
{children} <AudioElement />
<RadioElement />
</AudioContext.Provider>
);
};
AudioElement is a hidden <audio> tag rendered outside <Router>, so route changes, layout swaps and breakpoint changes can't unmount it. The seek bar and the play button get the element through a useAudio() hook that reads audioRef from context, which also removed some prop drilling.
Since then, whatever makes the sound gets mounted once at the top, and I place a WebSocket or a WebGL canvas that has to last the whole session the same way.
Redux holds the queue and keeps two players apart
The store started on plain createStore and later moved to Redux Toolkit with these slices: feature (queue, current song, index, volume, time), status (playing, repeat, shuffle, open panels), radio, theme, login, sidebar.
The queue comes from whatever list the song was in. Double-clicking a song in the chart makes the whole chart dataSongs:
const handleConfig = (data, song, index) => {
if (song._id === songCurrent._id) {
dispatch(statusSlice.actions.isPlayingChange(!isPlaying));
} else {
dispatch(statusSlice.actions.isPlayingChange(true));
}
dispatch(featureSlice.actions.setDataSongs(data));
dispatch(featureSlice.actions.setSongCurrent(data[index]));
dispatch(featureSlice.actions.setCurrentID(index));
// turn off radio when a playlist starts
dispatch(radioSlice.actions.setUrlRadio(''));
dispatch(radioSlice.actions.setIsPlayingRadio(false));
};
The queue panel renders dataSongs from the store, so it matches on every page. When currentIndex changes, an effect in AudioElement fetches the track by slug and sets songCurrent, which is where the <audio> src comes from.
Radio is different. Stations are live streams that go through React Player in a second hidden element, RadioElement. Starting a playlist clears the radio URL and starting a station sets isPlaying to false, while the play button in the middle reads urlRadio to work out which player it's toggling. It works, but nothing enforces one player at a time. Each handler has to remember to stop the other one.
A reload still cuts the music but keeps the song
A reload restarts the whole app. The audio element writes the position to localStorage on every timeupdate, and the song, queue and index get written when the song changes. On startup the slice reads those keys back as initial state:
export const featureSlice = createSlice({
name: 'feature',
initialState: {
dataSongs: DATA_SONGS_RECENT || [],
volume: VOLUME_STORAGE || 1,
songCurrent: SONG_RECENT_STORAGE ?? {},
currentIndex: CURRENT_ID_STORAGE ?? 0,
times: {
currentTime: CURRENT_TIME_STORAGE ? CURRENT_TIME_STORAGE : 0,
},
},
// ...
});
A one-time effect in AudioElement then seeks to the saved currentTime. isPlaying isn't stored, so after a reload you're on the same song and second, paused. I didn't plan that, but it matches browsers, which block audio until the user has interacted with the page.
This is fragile. The follow-up fixes (changing DATA_SONGS_RECENT ?? [] to || [], adding and later removing a dataSongs?.length > 0 guard) each patched a kind of stored data the code didn't expect. A small validation step on load would have replaced all of them.
times gets its own selector
timeupdate fires several times a second and dispatches setTimes each time. combinedStatusSelector pulled about twenty fields (playing state, queue, theme, login, sidebar...) into one object that almost every component used, times included. Every tick produced a new object, and the sidebar and song lists re-rendered several times a second.
I pulled times out:
// slice selector because when time changes it re-renders everything in combined
export const timesSelector = (state) => state.feature.times;
export const combinedFeatureSelector = createSelector(timesSelector, (times) => {
return { times };
});
Now only the seek bar, the time label and the audio element subscribe to it. That treats the symptom. The combined selector still returns a fresh object whenever any input changes, and the real fix is narrow selection, one useSelector per field or shallowEqual.
The queue logic needs rewriting first
Next, previous and track-end handling are spread across ControlsCenter and AudioElement, with let { currentIndex } = useSelector(...) mutated locally before dispatching. Shuffle exists twice and the two versions disagree. The Next button's version uses Math.ceil(Math.random() * length), which can return length (out of range) and never returns 0.
Repeat mode dispatches setTimes({ currentTime: 0 }) into a reducer that already wraps its payload, and the stored time ends up as a nested object. With next, prev and ended as reducer cases and a precomputed shuffle order, these bugs would have shown up early.
Persistence should be throttled to every few seconds plus once on pagehide, and store IDs only. Looking songs up by ID instead of slug would remove the hard-coded IDs in AudioElement that skip two songs sharing a slug. Every route in App.js also wraps itself in Wrapper and Controls, where one parent layout route with <Outlet /> would do it once.
The app still lacks the Media Session API, so on a locked phone there's no button that changes the track.
More posts
- 01
Deploying Next.js and NestJS to AWS EC2 with Docker Compose
How I deploy a pnpm monorepo to one EC2 box. Images get built in GitHub Actions and Docker Compose pulls them from GHCR. The server has no code.
- 02
How I store OAuth tokens for social media APIs in NestJS
OAuth for Facebook, TikTok and YouTube in a NestJS API. State and PKCE, encrypted tokens, refreshing before each publish, and when to ask for a reconnect.
- 03
llms.txt on my Next.js site, and now Lighthouse grades it
vennee.dev has a hand-written llms.txt and an llms-full.txt built from the blog. Notes on the spec, .txt routes in Next.js, and Lighthouse 13's new audit.