How to Use shouldRevalidate in Remix for Data Reload Control
In Remix, use the
shouldRevalidate function inside your route module to control when the loader should run again after navigation. Return true to reload data or false to skip reloading, optimizing performance and user experience.Syntax
The shouldRevalidate function is exported from a Remix route module. It receives an object with currentUrl, nextUrl, submission, and actionResult properties. You return true if you want Remix to re-run the loader and reload data, or false to skip it.
This lets you decide when to fetch fresh data after navigation or form submissions.
javascript
export function shouldRevalidate({ currentUrl, nextUrl, submission, actionResult }) { // return true to reload data // return false to skip reloading return true; }
Example
This example shows a route that only reloads data when the URL's search parameter refresh changes. Otherwise, it skips reloading to save network requests.
javascript
import { useLoaderData } from "@remix-run/react"; export async function loader({ request }) { const url = new URL(request.url); const refresh = url.searchParams.get("refresh"); return { time: new Date().toISOString(), refresh }; } export function shouldRevalidate({ currentUrl, nextUrl }) { return currentUrl.searchParams.get("refresh") !== nextUrl.searchParams.get("refresh"); } export default function RefreshTime() { const data = useLoaderData(); return ( <div> <p>Current time: {data.time}</p> <p>Refresh param: {data.refresh || "none"}</p> </div> ); }
Output
<div>
<p>Current time: 2024-06-01T12:00:00.000Z</p>
<p>Refresh param: none</p>
</div>
Common Pitfalls
- Returning
falsealways will prevent loaders from updating, causing stale data. - Not comparing relevant URL parts can cause unnecessary reloads or skipped updates.
- Ignoring
submissionoractionResultwhen needed can break form handling.
Always tailor shouldRevalidate logic to your app's navigation and data needs.
javascript
export function shouldRevalidate({ currentUrl, nextUrl }) { // Wrong: always false, data never reloads return false; } // Correct: reload only if pathname changes export function shouldRevalidate({ currentUrl, nextUrl }) { return currentUrl.pathname !== nextUrl.pathname; }
Quick Reference
shouldRevalidate controls when Remix reloads data after navigation or form actions.
- Return
trueto reload loader data. - Return
falseto skip reloading. - Use
currentUrlandnextUrlto compare navigation changes. - Use
submissionandactionResultto react to form submissions.
Key Takeaways
Use shouldRevalidate to control when Remix loaders re-run after navigation.
Return true to reload data, false to skip and improve performance.
Compare currentUrl and nextUrl to decide if data needs refreshing.
Consider form submissions with submission and actionResult parameters.
Avoid always returning false to prevent stale data issues.