Performance: useLoaderData hook
This affects how data is fetched and rendered on the page, impacting initial load speed and interaction readiness.
import { useLoaderData } from '@remix-run/react'; export async function loader() { const res = await fetch('https://api.example.com/data'); return res.json(); } export default function Page() { const data = useLoaderData(); return <div>{data.title}</div>; }
function Page() {
const [data, setData] = React.useState(null);
React.useEffect(() => {
fetch('/api/data')
.then(res => res.json())
.then(json => setData(json));
}, []);
if (!data) return <div>Loading...</div>;
return <div>{data.title}</div>;
}| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Client-side fetch with useEffect | Initial empty DOM, then update on fetch completion | Triggers 1 reflow per data update | Higher paint cost due to loading placeholder and re-render | [X] Bad |
| Server-side fetch with useLoaderData | DOM rendered once with data | Single reflow during initial paint | Lower paint cost, stable layout | [OK] Good |
useLoaderData hook in Remix?useLoaderData doesuseLoaderData in a Remix component?useLoaderData is imported from '@remix-run/react', not from 'remix' or 'react-router'.{ useLoaderData } from '@remix-run/react'.export async function loader() {
return { message: 'Hello Remix!' };
}
import { useLoaderData } from '@remix-run/react';
export default function Greeting() {
const data = useLoaderData();
return <h1>{data.message}</h1>;
}{data.message} inside an <h1> tag.useLoaderData? How to fix it?import { useLoaderData } from '@remix-run/react';
export default function Profile() {
const data = useLoaderData;
return <div>User: {data.name}</div>;
}useLoaderData without parentheses, so it is a function reference, not the data.const data = useLoaderData(); to get the loaded data.{ posts: [{id:1, title:'A'}, {id:2, title:'B'}] }. Which code correctly uses useLoaderData to render the post titles in a list?const { posts } = useLoaderData();posts.map to create list items with unique keys from post.id.Pass the test and this pattern moves unknown