The Challenge
Handling real-time audio playback in a single-page application presents unique challenges:
- Synchronizing global playback state with the browser's
HTMLAudioElement. - Preventing unnecessary re-renders when updating high-frequency data (like playback progress).
- Managing complex queue mutations (shuffle/repeat) across multiple feature modules.
The Solution (Architecture)
- Atomic Context Pattern: Instead of one large provider, I split the state into specialized contexts (Playback, Library, Queue) to satisfy the Interface Segregation Principle.
- Render-Phase Sync: Implemented a custom
useAudioEnginehook that synchronizes state during the render phase, making it resilient to React 19's concurrent rendering. - Type-Safe Ecosystem: Leveraged TanStack Router for file-based routing and TanStack Query for robust data fetching and caching.
Key Technical Wins
- Re-render Optimization: By decoupling the
PlaybackTimeContextfrom the mainMusicContext, I reduced the re-render surface area by ~80% during active playback. - Offline-First Persistence: Built a custom middleware layer for LocalStorage to ensure user playlists and likes persist across sessions with zero-latency updates.
- Performance-First Layout: Implemented an aggressive code-splitting strategy using
React.lazyandSuspenseskeletons for all non-critical UI, resulting in a lightning-fast initial TTI.
