Author: Joy kumar
 Mastering Remix Hooks: Simplify Data Fetching and Actions

Mastering Remix Hooks: Simplify Data Fetching and Actions

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.

useLoaderData();

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>();
  // ...
}

useActionData();

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>
  );
}

UseFetcher();

This hook used to fetch data from loader of another component without navigating to it.

Features:

  1. Trigger Loader.
  2. submit action function to any route without navigating to it.
  3. Track request status (e.g: loading, etc.).
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>
  );
}

useNavigate();

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("/");
      }}
    />
  );
}

UseParams();

This hook is used to access url parameter in Remix.

import { useParams } from "@remix-run/react";

function SomeComponent() {
  const params = useParams();
  // ...
}