Hooks refer to the Specific functions provided by remix to access some external features of application, Remix offers various amount of hooks.
Lets discuss some important hooks.
This hooks is used to access data from loader function and used futher on components
.
import { json } from "@remix-run/node";
import { useLoaderData } from "@remix-run/react";
export async function loader() {
return json(await fakeDb.invoices.findAll());
}
export default function Invoices() {
const invoices = useLoaderData<typeof loader>();
// ...
}
This hook is used to access data from action
function. Action function is used to submit data to server and useActionData
is used to access this data.
import { json } from "@remix-run/node";
import { Form, useActionData } from "@remix-run/react";
export async function action({ request }) {
const body = await request.formData();
const name = body.get("visitorsName");
return json({ message: `Hello, ${name}` });
}
export default function Invoices() {
const data = useActionData<typeof action>();
return (
<Form method="post">
<input type="text" name="visitorsName" />
{data ? data.message : "Waiting..."}
</Form>
);
}
This hook used to fetch data from loader of another component without navigating to it.
import { useFetcher } from "@remix-run/react";
export function loader() {
return { items: ["Apple", "Banana", "Cherry"] }; // Example loader data
}
export default function ItemList() {
const fetcher = useFetcher();
const fetchItems = () => {
fetcher.load("/items"); // Replace '/items' with your route
};
return (
<div>
<button onClick={fetchItems}>
{fetcher.state === "loading" ? "Loading..." : "Fetch Items"}
</button>
{fetcher.data && (
<ul>
{fetcher.data.items.map((item) => (
<li key={item}>{item}</li>
))}
</ul>
)}
</div>
);
}
This hook is used to navigate from one route to another programmatically, previously named useTransition();
import { useNavigate } from "@remix-run/react";
function SomeComponent() {
const navigate = useNavigate();
return (
<button
onClick={() => {
navigate("/");
}}
/>
);
}
This hook is used to access url parameter in Remix.
import { useParams } from "@remix-run/react";
function SomeComponent() {
const params = useParams();
// ...
}