Exploring useRevalidator and useRouteError Hooks in Remix

Exploring useRevalidator and useRouteError Hooks in Remix

The Remix web framework is one of the most modern tools that help build server-rendered applications. useRevalidator and useRouteError are powerful hooks introduced by Remix. They are helpful for data loading, state validation and error handling. Here in this blog, we will showcase both these hooks through simple examples explaining how to use them properly. 

useRevalidator – Keeping Data Fresh

What is useRevalidator?

useRevalidator is a Remix hook that can be used to manually revalidate data in a route. This can be helpful when the data on the page could change due to some user interactions like form submissions or external events.

How to Use It?

The useRevalidator hook returns an object with the following:

  • revalidate(): A function to trigger the revalidation process.
  • state: The current state of the revalidation process, either it is in idle or loading.

Example: Refreshing Data on Button Click

Let’s consider a very simple example where there’s a list of items shown fetched from the server, and the user can refresh the data by clicking the button.

import { useLoaderData, useRevalidator } from “@remix-run/react”;

export const loader = async () => {

  const items = await fetch(“https://api.example.com/items”).then((res) => res.json());

  return items;

};

export default function ItemList() {

  const items = useLoaderData();

  const { revalidate, state } = useRevalidator();

  return (

    <div>

      <h1>Items</h1>

      <button onClick={revalidate} disabled={state === “loading”}>

        {state === “loading” ? “Refreshing…” : “Refresh”}

      </button>

      <ul>

        {items.map((item) => (

          <li key={item.id}>{item.name}</li>

        ))}

      </ul>

    </div>

  );

}

Explanation

  • The loader function fetches the data from an API.
  • useRevalidator provides the revalidate function, which reloads the route data without a full page reload.
  • The button triggers revalidation and dynamically shows the loading state.

useRouteError – Simplified Error Handling

What is useRouteError?

useRouteError is a Remix hook for handling of errors that occur during data loading or actions in a specific route. It allows you to access the error object and display meaningful messages to users.

How to Use It?

When an error occurs in a loader, action, or default route handler, you can catch and render it using the useRouteError hook in an ErrorBoundary component.

Example: Displaying Error Messages

Here’s an example where we intentionally throw an error in the loader and handle it gracefully using useRouteError.

import { useRouteError } from “@remix-run/react”;

export const loader = async () => {

  throw new Error(“Failed to fetch data.”);

};

export function ErrorBoundary() {

  const error = useRouteError();

  return (

    <div>

      <h1>Error Occurred</h1>

      <p>{error.message}</p>

    </div>

  );

}

export default function ExampleComponent() {

  return <h1>This is a sample route</h1>;

}

Explanation

  • The loader function throws an error, simulating a failure.
  • The ErrorBoundary component catches the error and renders a fallback UI using the useRouteError hook.
  • Users see a friendly error message instead of a crash.

When to Use These Hooks?

  • useRevalidator: Ideal for scenarios where data needs periodic refreshing or updates based on user interactions.
  • useRouteError: Essential for displaying meaningful error messages when something goes wrong during data fetching or form submissions.

Conclusion

Remix’s useRevalidator and useRouteError hooks allow developers to build resilient and dynamic applications. By integrating these hooks, you can enhance user experience with real-time data updates and solid error handling.

Previous Article

How to Submit Form Data without Page Load in Shopify Remix App?

Next Article

Magento 2 Extensions Digest November 2024 (New Release & Updates)

Write a Comment

Leave a Comment

Your email address will not be published. Required fields are marked *

Get Connect With Us

Subscribe to our email newsletter to get the latest posts delivered right to your email.
Pure inspiration, zero spam ✨