We enhanced the type signatures of loader
/action
and
useLoaderData
/useActionData
to make it possible to infer the data type
from return type of its related server function.
To enable this feature, you will need to use the LoaderArgs
type from
@remix-run/node
instead of typing the function directly:
- import type { LoaderFunction } from "@remix-run/node";
+ import type { LoaderArgs } from "@remix-run/node";
- export const loader: LoaderFunction = async (args) => {
- return json<LoaderData>(data);
- }
+ export async function loader(args: LoaderArgs) {
+ return json(data);
+ }
Then you can infer the loader data by using typeof loader
as the type
variable in useLoaderData
:
- let data = useLoaderData() as LoaderData;
+ let data = useLoaderData<typeof loader>();
The API above is exactly the same for your route action
and useActionData
via the ActionArgs
type.
With this change you no longer need to manually define a LoaderData
type
(huge time and typo saver!), and we serialize all values so that
useLoaderData
can't return types that are impossible over the network, such
as Date
objects or functions.
See the discussions in #1254
and #3276 for more context.