0

I have a locally stored json in my project, which is an array containing around 200+ items.

Example: data.js

const data = [
  {
    title: 1
  },
  {
    title: 2 
  },
  ...
  {
    title: 200
  }
];

My Component:

import {data} from "../mocks/data.js";

I am thinking of a way to use the json data for sometime until I have a database setup, but importing 200+ records slows up the page.

Is there a way I can lazy load the locally json data?

2
  • Instead of storing it in a .js file, maybe you can do it by using hooks: const data = use(import('./data.json')).
    – chagatai
    Commented Jan 2, 2024 at 14:52
  • @chagatai do you have any examples, what is use here? Feel free post an answer.
    – bhansa
    Commented Jan 2, 2024 at 14:58

1 Answer 1

0

First of all, your example is a JavaScript object, not a JSON.

Secondly, The use hook may help you in this problem.

import { use } from 'react';

const data = use(import('./data.json'))

Also, there is a 3rd-party module to read in JSON data called json-loader, which is already included in create-react-app.

import customData from '../customData.json';

IMHO, I don't think that importing 200+ records in JSON slows up the page dramatically, but nevertheless these solutions may help you once you convert your mock data to a JSON.

1
  • I agree with you, but since its server side rendering with next js I wanted to have first paint quickly and load the data instead of render blocking due to data,
    – bhansa
    Commented Jan 4, 2024 at 6:48

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.