Utilizing lazy loading to import local JSON data in Next.js

I currently have a JSON file stored locally in my project, which is an array with over 200 items.

For example, the file is named data.js

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

Here is how I import it into my component:

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

While I am considering using this JSON data temporarily until I set up a database, importing all 200+ records at once is causing the page to load slowly.

Is there a way for me to implement lazy loading of this local JSON data?

Answer №1

To start, it's important to note that the example you provided is a JavaScript object, not JSON.

Additionally, utilizing The use hook could be beneficial for solving your issue.

import { use } from 'react';

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

Furthermore, there is a third-party module called json-loader that can assist in reading JSON data, and it comes pre-installed in create-react-app.

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

In my opinion, importing over 200 records as JSON should not significantly slow down the page load, but these solutions may be useful once you have converted your mock data into JSON format.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Display a hoverable button for a singular element within an array during the process of mapping through the array

const ChatWidget = () => { const bodyRef = useRef(null) const [{messages,roomMessages,roomID,socket,user}, dispatch] = useStateValue() const [dropdown, setDropdown] = useState(false) useEffect(()=>{ const setScreen = () =>{ bodyRef.cur ...

Exploring the power of internal linking with GatsbyJS

I am currently developing a website using gatsbyjs. I have concerns about the crawlability of "onClick" for SEO purposes and I would appreciate some assistance. This is my current code: render={data => ( <div className='feed'> ...

Issue with Tailwind CSS when applying @apply directive

click here Hello all, I am currently working on a Nextjs project and attempting to utilize the @apply processor. However, I am encountering an error message as shown above. This is my package.json: { "name": "simon-bask-health-app", ...

Prevent text from being split onto the next line

Currently, I am utilizing React, styled-components, and incorporating media queries. My media queries are set at three specific points: 480px, 768px, and 1200px. When scaling between these values on a desktop, the text loses its structure. I have been con ...

Adjusting the font size of floating labels within Material UI version 5

Is there an easy way to adjust the font size of floating labels for input fields in React MUI v5? I remember researching this issue a year ago when we were using version 4, and at that time it was difficult to change the cover area calculation behind the l ...

Variation in values across various functions within a state

Currently, I am working on a project using nextjs. I have a custom select component that opens the options when clicked, but I am struggling to figure out how to close it when clicking anywhere else on the screen. The state value seems to be causing some i ...

Ways to automatically adjust ideal camera position in R3F

I'm currently working on a model viewer and I've run into an issue where the camera position is consistently off when loading a 3D model (file type: GLB). While other online viewers seem to effortlessly adjust the camera angle regardless of the m ...

Struggling to overcome the CORS error when accessing a secured Google Cloud Function

I have set up a Google Cloud Function with credentials and authorized the origins http://localhost & http://localhost:3000. Additionally, I have granted my Google user account the cloudfunctions.functions.invoke role. Verification can be done by checki ...

Validation errors in the realm of Zod

Below is my code using Next.js 14 with TypeScript, React Hook Form, and Zod for validation. The issue arises when trying to display an error message for an empty form: import React from "react"; import category from "@/components/expenses/ca ...

Modifying the appearance of a Material-UI theme within a deeply embedded component

The structure of my components is as follows: App -> ThemeProvider -> MenuBar -> ThemeControls -> Switch and Autocomplete I aim to enable dark mode using the Switch component and adjust the primary color with the Autocomplete component. To ac ...

What are some ways that next.js Link can prevent unnecessary server requests?

Following that, there is a need to establish connections between these pages. While an HTML tag could be used for this purpose, it would result in server requests and page refreshes, which is not the desired outcome. import Link from 'next/link&apos ...

Error: Docker unable to locate package.json file

I'm encountering an issue. I tried building a project in Docker and received an error. The error states that during npm install, the package.json file could not be found. Here is my Dockerfile: FROM node #copy source COPY . /app # Install dependenc ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

Is there a way to execute a function after EACH user interaction?

I am in the process of developing a React Native kiosk application for an Android tablet that will be mounted on a wall. The main requirement is to include a "screen saver" feature, where if the user does not interact with the screen for 30 seconds, it wil ...

Unable to retrieve real-time data from Firestore using getStaticPaths in Next.js

While fetching data from Firebase Firestore using getStaticProps is successful, I encounter a 404 page when attempting to implement the logic for retrieving details of individual items with getStaticPaths. The current state of my [id].js code appears as fo ...

When it comes to next.js, those pesky trailing slashes have the power to guide me down a

Utilizing nextjs for enabling SSR in my application, the structure of the application is as follows: components - component1.js public - img1.png pages - /order [order].js [country].js contact-us.js review.js When navigating to 'localhos ...

What is the best way to maintain Redux state between Redux @init executions?

I am working on a React app that makes use of redux.js. One issue I encountered is related to a timeoutMonitor function that triggers when a user fails to complete a task within a set timeframe. This function dispatches a redux action (logoutUser()) and up ...

When utilizing the `useLocation` hook, the location information appears to be missing

When utilizing a HashRouter, and inside a component making use of useLocation, there seems to be an inconsistency between the window.location object and the location object retrieved from useLocation. While writing this, I have observed that there might b ...

What is the best way to implement caching for a Next.js page that utilizes getServerSideProps?

pages/stuff.ts export function getServerSideProps(context) { const userId = getUserIdOrNull(context); return {props: { somethingComplicated: getSomethingComplicated(!!userId) }}; } export default Home({somethingComplicated}) { return <div>{some ...

The React App causing the File Explorer in Windows to completely freeze up

After using the npm command to create a React app, my laptop's fan suddenly became louder and I encountered issues with File Explorer. Opening folders became unresponsive and it kept loading files indefinitely. This has greatly impacted my work produc ...