React Architecture: Advanced Navigation and Data Flow Patterns
A hands-on guide to data flow with React Router's data APIs. You keep filters and search in the URL with useSearchParams, load data before render with route loaders, share data from a layout through Outlet context, and show a global progress bar with useNavigation. The code uses current React Router imports and the full example was run with React Router 8.5.1.

In many single page apps, routing is treated as an afterthought: a way to swap one component for another. That leaves data fetching scattered across useEffect calls and filter state that vanishes on refresh. This guide is for React developers who want the router to carry the app's data flow instead. You will build three patterns with React Router's data APIs: URL-driven state, route loaders and Outlet context, plus a global loading bar.
This is part 22 of the Frontend & JavaScript Fundamentals series. It follows Context API vs. Redux, which covered app-wide state. Here the focus is state that belongs to a route.
Key takeaways
- If a value decides what the screen shows, keep it in the URL with
useSearchParams, so refresh and shared links show the same view. - Route loaders run before the route renders, so you avoid the render-then-fetch waterfall that
fetchinsideuseEffectcreates. - A layout route can pass data to its children with
<Outlet context>;useNavigationtells you when the next page is loading.
The core idea: the URL is the source of truth
A route loader is a function attached to a route that React Router calls before it renders that route, so the component gets its data on the first render. Loaders are one half of the idea. The other half is the URL.
Before writing code, ask one question about each piece of state. If the user refreshes the page, should they see the same thing? If they share the link, should a colleague see the same filtered view? When the answer is yes, internal React state (useState) is the wrong home for it.
A rule of thumb: if it decides what is displayed, it belongs in the URL. Things like an open dropdown or a half-typed form can stay in component state.
Imports changed in React Router 8
React Router 8 removed the react-router-dom package. Import hooks and createBrowserRouter from react-router, and RouterProvider from react-router/dom. The upgrade guide lists node@22.22+ and react@19.2.7+ (with the matching react-dom) as minimum versions. Install it with npm i react-router.
Pattern 1: query parameters for filters and search
A common anti-pattern is to keep a search box in useState and then try to sync that state to the URL. Read from the URL first instead. Here is a search filter that survives a page refresh, built with useSearchParams.
// DashboardFilter.jsx
import { useSearchParams } from 'react-router';
export const DashboardFilter = () => {
const [searchParams, setSearchParams] = useSearchParams();
const currentQuery = searchParams.get('q') || '';
const handleSearch = (event) => {
const query = event.target.value;
// Update the URL, not local state
setSearchParams(
(prev) => {
if (query) {
prev.set('q', query);
} else {
prev.delete('q');
}
return prev;
},
{ replace: true } // one history entry, not one per keystroke
);
};
return (
<input
type="search"
aria-label="Search automation logs"
value={currentQuery}
onChange={handleSearch}
placeholder="Search automation logs..."
/>
);
};
Checked against react-router@8.5.1 and react@19.3.1 on Node.js 22, 2026-10-30.
Why this works: there is no useState here. The input value comes straight from the URL. Edit the URL by hand and the input updates. That's what makes a dashboard view shareable.
Two details from the React Router docs matter here. Every call to setSearchParams causes a navigation, so { replace: true } keeps typing from filling the back button with one entry per letter. And the function form is not queued like React's setState: two calls in the same tick don't build on each other, so make all your changes inside one call.
Pattern 2: data loaders instead of fetch waterfalls
A common cause of slow React screens is "render, then fetch". A component renders, a useEffect fires, a spinner spins, and only then does data arrive. The react.dev useEffect page calls out the result: the parent fetches, renders its children, and only then do they start fetching. This is a network waterfall. The same page lists React Router as one of the tools that avoid it.
Loaders move the fetch out of the component. React Router's data loading guide says loaders are called before the route component is rendered, and the component reads the result with useLoaderData.
Here is a project details page:
// main.jsx
import { createBrowserRouter, useLoaderData, useRouteError, isRouteErrorResponse, data } from 'react-router';
import { RouterProvider } from 'react-router/dom';
import { createRoot } from 'react-dom/client';
// 1. The loader: the "backend" for this route
const projectLoader = async ({ params }) => {
const res = await fetch(`/api/projects/${params.id}`);
if (!res.ok) throw data('Project not found', { status: res.status });
return res.json();
};
// 2. The component only reads data
const ProjectDetails = () => {
// The data is already here on the first render
const project = useLoaderData();
return (
<div>
<h1>{project.name}</h1>
<p>Status: {project.status}</p>
</div>
);
};
// 3. The error boundary catches what the loader throws
const ProjectError = () => {
const error = useRouteError();
if (isRouteErrorResponse(error)) {
return <p>{error.status}: {error.data}</p>;
}
return <p>Something went wrong.</p>;
};
// 4. What shows on the very first page load, while the loader runs
const ProjectSkeleton = () => <p>Loading project…</p>;
// 5. The router config
const router = createBrowserRouter([
{
path: '/projects/:id',
Component: ProjectDetails,
loader: projectLoader,
ErrorBoundary: ProjectError,
HydrateFallback: ProjectSkeleton,
},
]);
createRoot(document.getElementById('root')).render(<RouterProvider router={router} />);
When the user follows a link, the router runs the loader first and renders the page once the data is ready. The component has no loading branch of its own.
The very first load is different: there is no previous page to keep on screen. The createBrowserRouter docs say that when no hydration data is provided, the loader runs during hydration and the route's HydrateFallback component renders in the meantime. Without one, the page stays blank and React Router logs a warning that no HydrateFallback was provided.
Fixed in this version
The earlier version imported from react-router-dom, which React Router 8 no longer ships. It also used an ErrorPage component that was never defined and threw a plain Error, so the boundary couldn't tell a 404 from a crash. The loader now throws data() with the HTTP status, which isRouteErrorResponse recognises.
Pattern 3: layouts and Outlet context
Most apps have a layout that stays put (a sidebar, a nav bar) and a content area that changes. Sometimes the layout needs to share data with the child page inside it.
Global stores such as Redux or Zustand can do this. For data that follows the route tree, React Router has a built-in option. The docs for useOutletContext describe it as a context provider built into <Outlet>, for the common case of a parent route sharing values with its children.
Imagine a workspace layout that already knows the user's role and passes it down:
// WorkspaceLayout.jsx
import { Outlet, useOutletContext } from 'react-router';
const Sidebar = () => <nav>Workspace menu</nav>;
// The parent layout
const WorkspaceLayout = () => {
// In a real app this would come from a root loader
const workspaceSettings = { theme: 'dark', role: 'admin' };
return (
<div className="workspace">
<Sidebar />
<main>
{/* Pass data down to any child route */}
<Outlet context={workspaceSettings} />
</main>
</div>
);
};
// The child route
const SettingsPage = () => {
const { role } = useOutletContext();
return (
<div>
<h2>Settings</h2>
{role === 'admin' ? <button type="button">Delete workspace</button> : <p>View-only permissions</p>}
</div>
);
};
Hiding a button is a display choice, not security. The server must still check the role before it deletes anything. If you use TypeScript, the React Router docs recommend that the parent export a small custom hook (for example useWorkspace()) that wraps useOutletContext, so children get proper types.
| Option | What it shares | Trade-off | When to use |
|---|---|---|---|
| URL search params | Filters, search, tabs, page number | Values are strings; every change is a navigation | Anything a shared link should reproduce |
Route loader + useLoaderData |
Data a route needs to render | Data lives per route, not app-wide | Fetching for a page or layout |
<Outlet context> |
Values from a layout to its child routes | Only reaches the direct child outlet | Layout data such as role or settings |
| Context or a store | App-wide state | More setup; not tied to the URL | Theme, auth session, cross-page caches |
Putting it together
Plan the route tree first. It decides the file layout and where each piece of data loads. A typical tree looks like this:
- Root route: loads the user's session.
- App layout: renders navigation and an error boundary for everything below.
- Feature routes (for example
/workflows): a loader fetches the list. - Detail routes (for example
/workflows/:id): a loader fetches one item. - Actions: route
actionfunctions handle form submissions. The route object docs say that when an action is called from<Form>,useFetcheroruseSubmit, the loader data on the page is revalidated automatically.
Handling loading states
Because the router waits for loaders, a navigation can feel stuck for a moment while data loads. The pending UI guide uses useNavigation for a global indicator: navigation.location is set while the next page loads.
// RootLayout.jsx
import { useNavigation, Outlet } from 'react-router';
const TopProgressBar = () => <div role="progressbar" aria-label="Loading page" />;
const RootLayout = () => {
const navigation = useNavigation();
const isNavigating = Boolean(navigation.location);
return (
<div>
{isNavigating && <TopProgressBar />}
<Outlet />
</div>
);
};
navigation.state gives more detail. It is "loading" while loaders run and "submitting" while an action runs, so you can style the two cases differently.
Why this design holds up
Routing is more than mapping paths to components. When the URL holds view state and the router owns data loading, your app gains three things:
- Resilience: refreshes and deep links show the same view.
- Speed: loaders start before render, so you skip effect-driven waterfalls.
- Less code: fewer
useEffectfetches and less global state for page data.
Next in the series, automated testing with Jest and React Testing Library shows how to test components like these.
Frequently asked questions
Is react-router-dom still needed?
Not in React Router 8. The upgrade guide says the react-router-dom package was removed. Import everything from react-router, except DOM-only APIs such as RouterProvider, which come from react-router/dom.
Should I use useSearchParams or useState for a search box?
Use useSearchParams when the search should survive a refresh or a shared link. Use useState for values that only matter while the user is on the page, such as an open menu. Passing { replace: true } keeps each keystroke from adding a history entry.
Do loaders replace TanStack Query or SWR?
Not always. Loaders decide when data loads for a route. A cache library adds features such as background refetching and sharing data across routes. The react.dev useEffect page lists React Router, TanStack Query and SWR as alternatives to fetching in effects, and some apps use a loader to fill a cache.
What is the difference between useLoaderData and useOutletContext?
useLoaderData returns what the current route's loader returned. useOutletContext returns whatever the parent layout passed to <Outlet context>. Use loaders for fetched data, and Outlet context for values the layout already has.
How do I show a 404 from a loader?
Throw data('Not found', { status: 404 }) from the loader. React Router renders the route's ErrorBoundary, where isRouteErrorResponse(error) is true and error.status is 404.
Sources
Verified against the sources below on October 30, 2026. Products and docs change often: check the linked sources if something looks different.
- React Router: Data mode installation
- React Router: Upgrading from v7
- React Router: useSearchParams
- React Router: Route object (data mode)
- React Router: Data loading
- React Router: createBrowserRouter (HydrateFallback)
- React Router: Error boundaries
- React Router: useOutletContext
- React Router: Pending UI
- react.dev: useEffect (alternatives to data fetching in Effects)
All 30 parts in this series
- Part 01Overcoming the Daunting Start: A Strategic Roadmap for New Frontend Developers
- Part 02Beyond the Tags: Mastering HTML Architecture for Product-Based Roles
- Part 03From Selectors to BEM: CSS Concepts You Must Know for Professional Projects
- Part 04Mastering the Primitives: A Builder's Guide to JavaScript Data Types and Functions
- Part 05Demystifying Scope and Closure: Key Concepts for Writing Robust JavaScript
- Part 06Beyond Frameworks: Practical DOM Manipulation Techniques for High-Performance UIs
- Part 07From Prototypes to ES6 Classes: Understanding JavaScript's Object-Oriented Nature
- Part 08Architecting Scalable JavaScript: OOP Principles & Design Patterns
- Part 09Mastering the Metal: Essential Web APIs & Browser Internals for Frontend Engineers
- Part 10Understanding the JavaScript Runtime: Event Loop, Call Stack, and Task Queue Explained
- Part 11Mastering Asynchronous Operations with JavaScript Promises: A Builder's Guide
- Part 12Modern Async Patterns: Making Asynchronous Code Readable with Async/Await and Generators
- Part 13Inside the V8 Engine: A Deep Dive into JavaScript Execution
- Part 14Demystifying CORS, HTTP, and Security: A Builder’s Guide
- Part 15REST vs. GraphQL: A Frontend Engineer’s Reality Check
- Part 16Secure Frontend Auth: The Definitive Guide to JWTs, Cookies, and Storage Strategies
- Part 17Why TypeScript Matters: Adding Type Safety to Your JavaScript Projects
- Part 18Getting Started with React: Deconstructing JSX and Component Architecture
- Part 19React Architecture: Mastering State and Props in Class vs. Functional Components
- Part 20Mastering React Hooks: From useState to Building a Production-Ready Custom Hook
- Part 21React State Management: Context API vs. Redux & Building a Theme Switcher
- Part 22React Architecture: Advanced Navigation and Data Flow Patterns
- Part 23Automated Testing in React: Unit Testing with Jest and React Testing Library
- Part 24Mastering Chrome DevTools: Debugging Techniques That Save Hours of Development Time
- Part 25Automating Code Quality: The Modern Stack with ESLint, Prettier, and Husky
- Part 26Demystifying the Build Pipeline: A Deep Dive into Webpack and Babel Configuration
- Part 27Improving Performance with Server-Side Rendering: Concepts and Implementation
- Part 28From Development to Production: A Builder's Guide to Frontend Deployment Strategies
- Part 29Introduction to Micro Frontends: Building Scalable Architectures
- Part 30The Frontend Architecture: From Junior Developer to Tech Lead
AI Automation Engineer & Salesforce Developer
Salesforce developer since June 2018. I build AI agents, n8n workflows and Salesforce integrations, and write up what holds up in real use.



Comments
Loading comments...