Article summary
Remix is a web framework with a versatile file-based routing structure. It allows for child routes to build on the components rendered in parent components. Another up side to Remix routing is that it also handles re-renders intelligently so that state changes in child components won’t force parent components to re-render.
Getting Data from a Parent Component
One downside is that remix routing splits pages across multiple routes. What happens when a child wants access to the result of a request performed in a parent? React can handle this by passing props from parent to child. Remix is different — each page is its own route, so we need something more specialized.
A custom React will enable child components to access the loader data from parents above it in the route tree. I am going to use the following tree to illustrate the file structure. The hook will be added to the /sales route which will allow the /sales/customer to get the customer’s name and ID.
app ├── root.jsx └── routes ├── sales │ └── customer.jsx └── sales.jsx
In the sales.jsx file add the following loader and hook definition:
export async function loader({ request }: LoaderArgs): {
result = Server.getData();
return {
id: result.id
name: result.name
};
}
type DataStructure = Awaited>;
export function useParentData() {
const data = useMatchesData("routes/parent");
return (data as DataStructure)
}
If you don’t have a useMatchesData hook provided with the remix init, here is the definition that came with the Remix blues stack:
useMatchesDataHook:
export function useMatchesData(
id: string
): Record | undefined {
const matchingRoutes = useMatches();
const route = useMemo(
() => matchingRoutes.find((route) => route.id === id),
[matchingRoutes, id]);
return route?.data;
}
Calling the Hook
Next in customer.jsx, call the hook inside of the exported component, and it will be able to access the data retrieved.
export default function Customer() {
const { id, name } = useParentData();
return { id, name }
}
Now the Customer component will use the result of the loader in the Sales file. Using this hook to load common information before a parameterized route is a good way to limit the number of calls between the server and the client.
Remix Routing
Remix’s file-based routing structure allows child routes to build on the components rendered in parent components and handles re-renders intelligently. This saves on computational resources and results in a faster web page.