Home > Software design >  Best practices for importing and using files in react
Best practices for importing and using files in react

Time:12-08

I currently load a component when you go to the url /hsk1game. I have 6 urls hsk1game hsk2game etc. My single component loads the different files based on the url. I import my files as such:

import Hsk1Data from '../HskFiles/hsk1.json';
import Hsk2Data from '../HskFiles/hsk2.json';
import Hsk3Data from '../HskFiles/hsk3.json';
import Hsk4Data from '../HskFiles/hsk4.json';
import Hsk5Data from '../HskFiles/hsk5.json';
import Hsk6Data from '../HskFiles/hsk6.json';

I currently put the files into an array and pull out the correct file according to the current url. This works fine but I feel it might be expensive. I can put the data into a database and then only make a single request instead of importing them all. But I was wondering if there's a better way with files?

Thank you

CodePudding user response:

So it depends on how much information is in those JSON files, people make a huge huff about performance when the reality is unless you are working with LOTS of data then its really negligible.

If your JSON files are massive, i'd recommend using the second method you described and returning that information via a request, because it won't be required by the bundler and so will reduce the amount of data that needs to be transferred when the page first loads.

If the JSON files are reasonably small, there is nothing wrong with just importing them.

  • Related