How can you preload data for a route in React

0 votes
Can i know How can you preload data for a route in React?
Feb 22 in Node-js by Nidhi
• 11,580 points
97 views

1 answer to this question.

0 votes

Preloading Data for a Route in React (React Router v6.4+)

You can preload data using the loader function in createBrowserRouter. This fetches data before rendering the component.

1. Define a Route with a loader

import { createBrowserRouter, RouterProvider } from "react-router-dom";

import Home from "./Home";

import PostDetails from "./PostDetails";

const router = createBrowserRouter([

  {

    path: "/",

    element: <Home />,

  },

  {

    path: "/post/:id",

    element: <PostDetails />,

    loader: async ({ params }) => {

      const response = await fetch(`https://jsonplaceholder.typicode.com/posts/${params.id}`);

      return response.json();

    },

  },

]);

const App = () => <RouterProvider router={router} />;

export default App;

2. Access Preloaded Data Using useLoaderData

import { useLoaderData } from "react-router-dom";

const PostDetails = () => {

  const post = useLoaderData(); // Retrieves preloaded data

  return (

    <div>

      <h2>{post.title}</h2>

      <p>{post.body}</p>

    </div>

  );

};

export default PostDetails;

answered Feb 24 by Kavya

Related Questions In Node-js

0 votes
1 answer
0 votes
1 answer
0 votes
1 answer

How do you handle a large amount of data in React?

Handling Large Amounts of Data in React To ...READ MORE

answered Feb 24 in Node-js by Kavya
68 views
0 votes
1 answer
0 votes
1 answer

How to pass parameters with react-router?

Passing Parameters with React Router 1. Define a ...READ MORE

answered Feb 23 in Node-js by Kavya
90 views
0 votes
1 answer

What is the use of Switch in React Router?

In React Router v5, <Switch> is used ...READ MORE

answered Feb 23 in Node-js by Kavya
47 views
0 votes
1 answer

How do you create protected routes in React?

Creating Protected Routes in React (React Router ...READ MORE

answered Feb 23 in Node-js by Kavya
76 views
0 votes
1 answer
0 votes
1 answer

How to Handle Jest Unit Testing for 'ɵcmp' in a React-in-Angular Hybrid App?

Encountering the 'ɵcmp' property error during Jest ...READ MORE

answered Dec 23, 2024 in Node-js by Navya
89 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP