Building React Apps: Weather, Music and Video · Course book
Chapter 2: A Music Player with Redux
A music streaming app is a step up from a single-page data display. Many screens, a discovery page, charts, song and artist details, search and a page of music popular near you, all draw on the same external music API, while a player at the bottom of the screen keeps playing as the user moves between them. That combination of shared server data and shared player state is exactly what state-management tools are for. This chapter explains how such an app is built with React 18, Tailwind CSS and Redux Toolkit, using RTK Query to fetch from a music API offered through the RapidAPI marketplace. It covers the layout and routing, fetching and caching data, the player's state and controls, the detail pages, location-based charts, search and deployment.
Layout, routing and styling
The app has a fixed structure: a sidebar of links on the left, a scrolling main area in the middle that changes with the route, a top play panel on wide screens showing top charts and artists, and a music player bar fixed to the bottom. React Router maps paths such as /, /top-artists, /around-you, /songs/:songid, /artists/:id and /search/:searchTerm to page components, while the sidebar, top play panel and player stay mounted outside the routes so that the music never stops when the page changes.
Tailwind CSS styles everything with utility classes written directly in the markup, such as flex flex-col w-[250px] p-4 bg-[#191624]. Responsive prefixes such as md: and xl: switch styles at breakpoints: the sidebar can collapse into a menu button on phones, and the top play panel can move below the content on narrower screens. Tailwind's approach keeps styles next to the components they belong to and avoids naming hundreds of CSS classes.
Fetching and caching with RTK Query
The music data comes from an API on RapidAPI, a marketplace that gives access to many APIs with a single key, sent in request headers. Instead of writing fetch calls in every component, the app defines all endpoints once with RTK Query, part of Redux Toolkit.
export const musicApi = createApi({
reducerPath: "musicApi",
baseQuery: fetchBaseQuery({
baseUrl: API_BASE,
prepareHeaders: (headers) => {
headers.set("X-RapidAPI-Key", import.meta.env.VITE_RAPID_API_KEY);
return headers;
},
}),
endpoints: (builder) => ({
getTopCharts: builder.query({ query: () => "/charts/world" }),
getSongDetails: builder.query({ query: ({ songid }) => `/tracks/details?track_id=${songid}` }),
}),
});
export const { useGetTopChartsQuery, useGetSongDetailsQuery } = musicApi;
RTK Query generates a hook for each endpoint. A component calls const { data, isFetching, error } = useGetTopChartsQuery() and receives the data, a loading flag and any error, so it can show a Loader component while fetching and an Error component if something fails. (The endpoint paths above are illustrative; each music API has its own.)
The bigger benefit is caching. Results are stored in the Redux store under a key made of the endpoint and its arguments. If two components on the same page ask for the top charts, only one request is sent; if the user leaves a page and returns while the data is still cached, no request is sent at all. RTK Query keeps unused data for 60 seconds by default, and the period can be changed.
Player state and controls
Which song is playing, whether it is paused, and the list it came from must be known everywhere: by every song card, by the detail pages and by the player bar. That shared client state lives in a Redux slice, separate from the cached server data.
| State field | Meaning | Changed by |
|---|---|---|
| currentSongs | The list the playing song came from | Clicking play on any card in a list |
| currentIndex | Position of the playing song in that list | Play, next and previous |
| activeSong | The song object now playing | Play, next and previous |
| isPlaying | Whether audio is currently playing | The play and pause buttons |
| genreListId | The genre chosen on the Discover page | The genre drop-down |
Each song card shows the cover art and a play or pause button that appears on hover, and highlights itself if it is the active song. Clicking play dispatches an action with the song, its list and its index; clicking pause dispatches a pause action. The player bar contains an HTML <audio> element whose source is the active song's preview URL, plus controls. A React effect calls the element's play() or pause() method whenever isPlaying changes.
The controls are small calculations. Next moves to index (i + 1) mod n, so after the last of 10 songs, at index 9, it wraps to 0; previous moves to (i − 1 + n) mod n. Shuffle picks a random index instead. The seek bar is a range input whose value is the audio's current time: for a 213-second song, the display shows 3:33, found as 213 / 60 = 3 minutes with 33 seconds left over, and dragging the bar to 40 percent sets the time to 0.4 × 213 = 85.2 seconds, shown as 1:25. Volume is another range input from 0 to 1, and a repeat toggle restarts the same song when it ends instead of advancing.
Detail pages, charts near you and search
The Discover page lists songs for the selected genre, chosen from a drop-down whose value is stored in Redux, so returning to the page remembers it. A Top Play panel shows the top five chart songs as compact rows and top artists in a horizontally swiping carousel made with the Swiper library, which handles touch gestures and responsive numbers of visible slides.
The song details page reads the song id from the URL with useParams, fetches the song's details, including lyrics where available, and its related songs, and lists them with the same row component and play buttons. The artist details page does the same for an artist, showing their picture, genre and top songs. Reusing small components across pages, a header component for both details pages and a row component for every list, keeps the code short.
The Around You page shows songs popular in the user's country. The app first asks a geolocation service for the country code of the visitor's internet address, then requests the chart for that country. Because this sends information about the visitor to another service, a real app should mention it in its privacy notice and fall back gracefully, for example to the world chart, if the lookup fails. Search reads the term from a form in the top bar, navigates to /search/term, and the search page fetches matching songs and artists.
Polishing and deploying
Real API data is messy, so components must cope with missing fields. Some songs have no preview audio, some artists have no picture and some tracks have no lyrics. Optional chaining, such as song?.images?.coverart, avoids crashes when a field is absent, and sensible fallbacks, a placeholder image or the message "Sorry, no lyrics found", keep the page looking deliberate rather than broken. Song cards should also disable the play button for tracks without audio rather than failing silently when clicked.
Performance deserves a look too. Cover images are the heaviest part of most pages, so they should be shown at a sensible size and loaded lazily below the fold. Long lists can be limited, for example to the first 10 top artists in the carousel, with a link to the full page. The browser's developer tools show how many requests each page makes and how large they are, a quick way to confirm that caching is doing its job.
The finished app is a static build, so deployment is straightforward: npm run build produces a folder of files that any static host can serve. Two settings matter. The RapidAPI key is set as an environment variable in the host's dashboard, and the host must be told to serve index.html for every path, a "single-page app" rewrite rule, so that refreshing a page such as /top-artists does not return a 404 error. As with any key that reaches the browser, treat it as visible to users and choose an API plan whose limits you are comfortable with.
Practice tasks
- A list has 12 songs and the current index is 11. What index do next and previous give?
- Format a song length of 187 seconds as minutes and seconds, and give the time after seeking to 75 percent.
- Repeat the caching worked example for this sequence: Discover, Top Charts, song A, song B, song A, Discover. How many requests are made with and without caching?
- Explain why the player bar must be rendered outside the router's page components.
- Which data belongs in the RTK Query cache and which in the player slice? Give two examples of each.
- Describe a sensible fallback for the Around You page when the visitor's country cannot be found.
This course book is available to read online only at tech-academy.chrysolites.org.