React Lazy Load Required Files

I have 20 to 25 mp3 files in my react app. User have the ability to setup any one song. The problem is whenever the React app loads, all the songs are imported by default. But i want to import only one song which user have selected so the app can load faster. I have created customhook useSound which takes song name and it return the mp3 file. Below is the code. // File 1, where useSound is used
const getSound = useSound('song1');
getSound.volume = 0.5;
getSound.play();
const getSound = useSound('song1');
getSound.volume = 0.5;
getSound.play();
// File 2: useSound Implementation
import song1 from "../../assets/songs/song1.mp3"
import song2 from "../../assets/songs/song2.mp3"
...
import song25 from "../../assets/songs/song25.mp3"

export const useSound = (value) => {
if (value == "song1") return new Audio(song1);
if (value == "song2") return new Audio(song2);
...
if (value == "song25") return new Audio(song25);
}
import song1 from "../../assets/songs/song1.mp3"
import song2 from "../../assets/songs/song2.mp3"
...
import song25 from "../../assets/songs/song25.mp3"

export const useSound = (value) => {
if (value == "song1") return new Audio(song1);
if (value == "song2") return new Audio(song2);
...
if (value == "song25") return new Audio(song25);
}
Can anyone help and tell me a better approach for this?
3 Replies
dzenda
dzenda•3mo ago
Don't import the songs . Put them into the /public folder and load them from there. If that's possible Option 2) have a server action that takes the "songid" reads it from fs or imports it idk and then returns the correct one Let me know if you got my point or if you need a code example.
Noor
Noor•3mo ago
Thanks. I tried the dynamic import and it's working.
dzenda
dzenda•3mo ago
okay just consider hosting you files on a CDN or some storage bucket . Because it could be used a a ddos vector . 🤔 but if its a small private app it probably doesn't matter
Want results from more Discord servers?
Add your server
More Posts