12

I want to implement lazy loading in my React app but most of the files are JSON. Few of them are loading when the viewport width is less than e.g. 768px and I don't want to load them in the Desktop app when they are not needed. Is there any way to load the JSON file with React.lazy()?

My JSON file is generated with Adobe After Effect extensions called: 'Bodymovin' and later I am importing this file like this:

import * as background from './background.json';
import * as backgroundLarge from './background-large.json';
import * as backgroundMedium from './background-medium.json';
import * as backgroundMobile from './background-mobile.json';
import * as backgroundSmallMobile from './background-smallMobile.json';
import * as tree from './tree.json';
import * as treeLarge from './tree-large.json';
import * as treeMedium from './tree-medium.json';
import * as treeMobile from './tree-mobile.json';
import * as treeSmallMobile from './tree-smallMobile.json';

I was trying to load it normally like any other components with default export but it's not working.

const treeMedium = lazy(() => import('./tree-medium.json'));

When I import JSON normally I am using it later like this:

backgroundOptions: {
      loop: true,
      autoplay: true,
      animationData: background.default,
    },

And pass this object into Lottie component from react-lottie

Can I convert it to lazy loading or I am thinking wrong?

1 Answer 1

26

It's not a React component, so you shouldn't wrap it with a lazy call.
Basically you just need to load it and handle a promise.
Something like:

componentDidMount() {
 import('./tree-medium.json').then(background => {
  this.setState({ background })
 })
}

and then use it somewhere in your render

UPD 2023: using hooks

const [data, setData] = useState(null);
  
useEffect(() => {
  import('./data.json').then(data => {
    setData(data);
  });
}, []);
Sign up to request clarification or add additional context in comments.

1 Comment

As for 2023, let's not forget about use hook: const data = use(import('./data.json'))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.