Learn Remix Β· 5/13

Elevating the UX: Pending States & Optimistic UI

9 min read

markdown
Hello there! Welcome to the FreeCodeCamp guide. Let's dive into making your Remix applications feel incredibly fast and responsive for your users. Today, we're tackling how to handle the moments *between* a user's action and the server's response. Let's make waiting feel like a thing of the past! πŸš€

## Elevating the UX: Pending States & Optimistic UI

When a user interacts with your web application, like submitting a form or clicking a "like" button, there's a brief period where the browser is communicating with the server. If the user gets no feedback during this time, they might think the app is broken or impatiently click the button again. This leads to a clunky and confusing user experience (UX).

In this guide, you'll learn how to provide clear feedback during these pending states and even make your app feel instantaneous with a technique called "Optimistic UI".

---

### 1. The `useNavigation` Hook: Tracking Global Page Transitions

First up, let's get a handle on what the application is doing at any given moment.

#### πŸ€” **Definition & Problem**

**Definition:** The `useNavigation` hook is a tool provided by Remix that gives you information about any page-to-page navigation that is currently happening.

**The Problem:** Imagine a user filling out a long sign-up form. They click "Create Account", and... nothing happens visually. Is the form submitted? Is the internet slow? Did the click even register? In their confusion, they click the button five more times, accidentally creating multiple accounts. This is a classic UX failure. We need a way to know *when* the application is busy navigating or submitting data so we can give the user feedback.

#### βœ… **How `useNavigation` Solves It**

The `useNavigation` hook returns an object with a `state` property. This `state` can be in one of three conditions:

*   `'idle'`: Nothing is happening. The app is waiting for the user to do something.
*   `'loading'`: The app is navigating to a new page and is fetching the data for the next route.
*   `'submitting'`: The app is sending data to the server from a `<Form>` submission (POST, PUT, DELETE, etc.).

By checking this `state`, we can dynamically change what the user sees.

#### πŸ’» **Hands-On Example**

Let's look at a simple contact form. We want to disable the "Submit" button and change its text while the form is being submitted.

```jsx
import { Form, useNavigation } from "@remix-run/react";

export default function ContactForm() {
  const navigation = useNavigation();

  // The 'submitting' state is true if navigation.state is "submitting"
  const isSubmitting = navigation.state === "submitting";

  return (
    <Form method="post">
      <label>
        Name: <input name="name" type="text" />
      </label>
      <label>
        Message: <textarea name="message" />
      </label>
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting ? "Submitting..." : "Submit"}
      </button>
    </Form>
  );
}

What's happening here?

  1. We import useNavigation from @remix-run/react.
  2. We call the hook to get the current navigation object.
  3. We create a boolean variable isSubmitting for readability.
  4. In the <button>, we use the disabled attribute to prevent more clicks if isSubmitting is true.
  5. We also change the button's text to "Submitting..." as a clear visual cue.

This simple change dramatically improves the user experience by preventing duplicate submissions and clearly communicating that the application is working. ✨


2. UX Polish: Disabling Buttons and Showing Loading Spinners

Disabling a button is great, but we can do even better. Let's add more visual feedback.

πŸ€” Definition & Problem

Definition: UX Polish refers to small, refined interactions that make an application feel more professional and intuitive. This includes things like loading spinners, subtle animations, and clear state indicators.

The Problem: While "Submitting..." is good text feedback, a visual indicator like a spinner is a universally recognized symbol for "processing." It's often more effective at grabbing the user's attention and assuring them that something is happening in the background.

βœ… How to Implement It

We can expand on our previous example using the same useNavigation hook. There's no new concept to learn, just a better application of the isSubmitting state.

πŸ’» Hands-On Example

Let's add a simple spinner to our form button.

jsx
import { Form, useNavigation } from "@remix-run/react";

// A simple SVG spinner component
function Spinner() {
  return (
    <svg
      className="animate-spin"
      /* ... other SVG attributes for styling */
    >
      {/* ... path data for the spinner */}
    </svg>
  );
}

export default function ContactForm() {
  const navigation = useNavigation();
  const isSubmitting = navigation.state === "submitting";

  return (
    <Form method="post">
      {/* Form inputs go here */}
      <button
        type="submit"
        disabled={isSubmitting}
        className="flex items-center justify-center" // Using CSS for layout
      >
        {isSubmitting ? (
          <>
            <Spinner />
            <span>Submitting...</span>
          </>
        ) : (
          "Submit"
        )}
      </button>
    </Form>
  );
}

What's happening here?

  • We've created a reusable <Spinner /> component.
  • When isSubmitting is true, we now render the spinner alongside the text.
  • This provides immediate, language-agnostic feedback that the app is busy. It's a small change with a big impact on how professional your app feels.

Fun Fact: The circular loading spinner (officially called a "throbber") was invented by Netscape Navigator in the mid-1990s. Its logo would animate while a page was loading. It was so effective that the concept has stuck around for decades!


3. The useFetcher Hook: Mutations Without Page Navigation

Sometimes, you want to change data on the server without navigating to a new page. Think "liking" a tweet or adding an item to a cart. A full page reload for such a small action would be overkill.

πŸ€” Definition & Problem

Definition: The useFetcher hook in Remix allows you to trigger server actions and load data without causing a full page navigation. It's like having a tiny, dedicated form that manages its own loading state.

The Problem: On an e-commerce product page, a user clicks "Add to Cart." If the whole page reloads, they lose their scroll position and the experience feels clunky. They just wanted to perform one small action, not navigate somewhere else.

βœ… How useFetcher Solves It

A fetcher has its own state (idle or submitting) and its own special component, <fetcher.Form>, which works just like a regular <Form> but doesn't trigger a global useNavigation state change. This isolates the loading state to just the component that needs it.

πŸ’» Hands-On Example

Imagine a "subscribe to newsletter" form in the footer of your website.

jsx
import { useFetcher } from "@remix-run/react";
import { useEffect, useRef } from "react";

export function NewsletterForm() {
  const fetcher = useFetcher();
  const formRef = useRef(null);

  // Check if the submission was successful
  const isSuccess = fetcher.data?.ok === true;

  // Reset the form after a successful submission
  useEffect(() => {
    if (isSuccess) {
      formRef.current?.reset();
    }
  }, [isSuccess]);


  return (
    <fetcher.Form method="post" action="/subscribe" ref={formRef}>
      <input type="email" name="email" placeholder="Enter your email" />
      <button type="submit" disabled={fetcher.state === 'submitting'}>
        {fetcher.state === 'submitting' ? 'Subscribing...' : 'Subscribe'}
      </button>

      {isSuccess && <p>Thanks for subscribing!</p>}
      {fetcher.data?.ok === false && <p>Oops! Something went wrong.</p>}
    </fetcher.Form>
  );
}

What's happening here?

  1. We use useFetcher() to get a fetcher object.
  2. We use <fetcher.Form> instead of <Form>. This is crucial!
  3. We check fetcher.state (not navigation.state) to disable the button.
  4. The form posts to an /subscribe action route, but the user stays on the current page.
  5. fetcher.data will hold the return value from your action. This is how we can show success or error messages without navigating.
  6. We use a useEffect to clear the form on success, making it ready for another submission. This is a common and user-friendly pattern.

4. Optimistic UI: Faking Instant Updates

This is where we make your application feel magical. ✨

πŸ€” Definition & Problem

Definition: Optimistic UI is a pattern where you update the user interface immediately after a user action, assuming the server request will succeed. You show the final state before the server has even confirmed it.

The Problem: A user leaves a comment on a blog post. They click "Post Comment," see a spinner for a second, and then their comment appears. This is good, but it doesn't feel instant. For actions that are likely to succeed, we can do better.

βœ… How Optimistic UI Solves It

We can "predict" the outcome of the action and render the new UI state right away. If the server comes back with an error (the pessimistic case), we can then roll back the change and show an error message. But 99% of the time, the action succeeds, and the user experiences zero delay.

πŸ’» Hands-On Example

Let's build a "like" button. When the user clicks it, it should immediately look "liked."

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

// Assume `post` is the data for a blog post, including `post.likes` (a number)
// and `post.isLikedByCurrentUser` (a boolean)
function LikeButton({ post }) {
  const fetcher = useFetcher();

  // The optimistic part!
  // We check the data being sent in the fetcher's submission.
  // If the user is submitting the "like" action, we pretend the like count is higher.
  let optimisticLikes = post.likes;
  if (fetcher.formData) {
    // This runs ONLY during the submission
    optimisticLikes += 1;
  }

  // Determine the button's state. Is it currently liked?
  // We'll say it is if the server has confirmed it OR if we're optimistically liking it.
  const isLiked = optimisticLikes > post.likes || post.isLikedByCurrentUser;

  return (
    <fetcher.Form method="post" action="/likes">
      {/* Hidden input to send the post ID */}
      <input type="hidden" name="postId" value={post.id} />

      <button name="intent" value="like" type="submit">
        {/* The button's text and style change instantly on click */}
        ❀️ {isLiked ? "Liked" : "Like"} ({isLiked ? optimisticLikes : post.likes})
      </button>
    </fetcher.Form>
  );
}

What's happening under the hood?

  1. When the user clicks the "Like" button, the <fetcher.Form> submits.
  2. During this submission, fetcher.formData is no longer null. It contains the data being sent (postId and the button's intent).
  3. Our if (fetcher.formData) block immediately runs. We create an optimisticLikes variable that is one greater than the actual server state.
  4. The component re-renders instantly, showing the new optimisticLikes count and the "Liked" state before we've heard back from the server.
  5. Once the server action completes, Remix revalidates the data, and the post.likes prop will update to the true value from the database. Since our optimistic value matches the new true value, the user sees no flicker or change.
  6. If the server action had failed, fetcher.formData would become null again, the optimistic code would stop running, and the UI would revert to the original post.likes count.

This technique is incredibly powerful for making your app feel lightning-fast and is a hallmark of modern, high-quality web applications.


πŸ“š Further Reading & References

To go deeper, check out the official Remix documentation. They are the ultimate source of truth!

Happy coding! You're now equipped to build smoother and more delightful user experiences in Remix. πŸŽ‰

text

Challenge

You are tasked with building a highly responsive LikeButton component in a Remix application. This component should allow users to like or unlike a post without a full page navigation and provide immediate visual feedback.

Requirements:

  1. Use useFetcher: The component must use the useFetcher hook to handle the form submission for liking/unliking. This will prevent a full page reload.
  2. Form Submission: The <fetcher.Form> should submit a POST request. It must include a hidden input with name="intent" and a value of either "like" or "unlike" based on the current liked status.
  3. Pending UI State: While the form is submitting (fetcher.state === 'submitting'), the button must be disabled, and its text should change to "Liking..." or "Unliking..." to provide clear feedback to the user.
  4. Optimistic UI: Implement an optimistic update for the like count and button appearance. The UI should update immediately upon clicking the button, before the server has responded. You will need to use fetcher.formData to predict the outcome of the action.

Expected result

Your final code should be a complete React component named LikeButton that correctly implements the following:

  1. useFetcher Hook: The useFetcher hook is initialized at the top of the component.
  2. Optimistic State Calculation: Logic is in place to determine the optimistic isLiked status and likeCount. This logic inspects fetcher.formData to see if an action is in flight. If fetcher.formData exists, the optimistic state should be the opposite of the original isLiked prop, and the count should be adjusted accordingly.
  3. Pending State Management: A variable, for instance isSubmitting, is derived from fetcher.state === 'submitting'. This variable is used to disable the button and change its text during submission.
  4. fetcher.Form: The JSX contains a <fetcher.Form method="post">. Inside the form, there is:
    • A <button> element with its disabled attribute set to the isSubmitting variable.
    • The button's text dynamically changes based on isSubmitting (e.g., from "Like" to "Liking...").
    • A hidden <input> with name="intent" and its value dynamically set to "like" or "unlike".
  5. The like count displayed on the page correctly reflects the optimistic value.
jsx

Solve the challenge, then check it.

Ctrl+Enter

Course complete!

You've passed every challenge in this course.