nextjs useEffect load json data


To load data from a JSON file in a Next.js application, you can use the useEffect hook to fetch the data in the component. Here’s an example of how you can do this:

import { useEffect, useState } from 'react'

function MyComponent() {
  const [data, setData] = useState(null)

  useEffect(() => {
    async function loadData() {
      const res = await fetch('/data.json')
      const json = await res.json()
  }, [])

  if (data === null) {
    return <p>Loading data...</p>

  return (
      <h1>My Data</h1>
      <pre>{JSON.stringify(data, null, 2)}</pre>

export default MyComponent

In this example, the useEffect hook is used to fetch the data from the /data.json file when the component is mounted. The data is stored in the data state variable, and a loading message is displayed while the data is being fetched.

Once the data is loaded, it is displayed in the component. You can customize the component to display the data in any way you like.

Keep in mind that you’ll need to make sure the data.json file is available at the specified URL. You can do this by including the file in the public directory in your project, or by using a server to serve the file.