How to use useLoaderdata hook in React router
React adopts a component-based architecture that allows developers to create reusable code sections. Hooks are the latest addition to React, which enables state management. They make our code concise, readable, and maintainable by adding state and other features to functional components. One of the hooks we will be going over is the useLoaderData hook. This hook greatly increases the user experience by loading any data from your routes even before they are rendered, preventing any empty states.
Benefits of the useLoaderData hook
Some of the benefits of the useLoaderData have been highlighted below. We’ll see more of these with tangible proof from a working React application.
Fetching data before it is rendered speeds up network requests, greatly increasing the web app’s performance.
Empty states are not displayed to the user if data is available to components in the pre-rendering stage.
Providing website data as quickly as possible provides a seamless user experience.
The code modularity is enhanced, and the developer has made a cleaner component design available by writing clear and concise code sections.
React application
The React app below uses the useLoaderData to fetch data from a public API endpoint, https://random.dog/woof.json, that displays a random dog picture on the Pet gallery page.
import React from 'react';
import {createBrowserRouter, createRoutesFromElements, Route, Link, Outlet, RouterProvider} from 'react-router-dom';
import './App.css';
import {HomeEducative} from "./HomeEducative"
import {DataEducative,load_my_api_data } from "./DataEducative"
import {ContactEducative} from "./ContactEducative"
function App(props) {
const educative_router = createBrowserRouter(
createRoutesFromElements(
<Route path="/" element={<Root />}>
<Route index element={<HomeEducative />} />
<Route path="/contact_educative" element={<ContactEducative />} />
<Route path="data_educative" element={<DataEducative />} loader={load_my_api_data} />
</Route>
)
)
return (
<div className="App">
<RouterProvider router={educative_router} /> {/* router is the prop */}
</div>
);
}
const Root = () => {
return <>
<div class="educatives_styles">
<Link class="flex_item_one" to="/">Homepage</Link>
<Link class="flex_item_one" to="/data_educative">Pet Gallery</Link>
</div>
<div>
<Outlet />
</div>
</>
}
export default App;Code explanation
The following is a line-by-line explanation of the code above:
In the DataEducative.jsx file:
Line 1: We import the
useLoaderDatahook from thereact-router-domlibrary.Lines 2–12: We define
DataEducative, a functional component that will preload data from the router using theuseLoaderDatahook and assign its value toeducative_dog_object_url. We then display the image fetched from the public API using theimgtag.Lines 15–19: We define an asynchronous loader function called
load_my_api_data. We call it a loader function because it hits the public API,https://random.dog/woof.json, using thefetchmethod and returns a JSON object. From that API endpoint, it returns the URL property.
In the App.jsx file:
Lines 1–6: In this section, we import some necessary modules and custom-made components—
HomeEducative,DataEducative, andContactEducative.Lines 8–16: We define the app function component, which initializes the
educative_routerobject using thecreateBrowserRouterrouter andcreateRoutesElementshelper, which helps configure routes. TheRootelement is routed to the"/"path,ContactEduactiveto"/contact_educative", index page toHomeEducative, andDataEducativeto"data_educative"path respectively.Lines 18–22: The entire
educative_routeris wrapped around theRouterProvidercomponent by passing it as aprop. Arguments of React components are called props. Lines 24–35: We define a
Rootfunctional component. This component will be rendered when the user accesses theRoots path. TwoLinkcomponents have been used to navigate to theHomepageandPet Gallerypages. We have also used theOutletcomponent to render each child component’s UI content.
Summary
To wrap things up, the useLoaderData hook in React significantly enhances the user experience by optimizing data loading before component rendering, thus eliminating empty states and providing faster access to website content. This hook not only improves performance but also promotes code modularity and cleaner component design, as demonstrated in the provided example. By abstracting data loading logic into a reusable hook, developers can achieve more concise, readable, and maintainable code, leading to a smoother development process and enhanced application quality.
Free Resources