Elevating the UX: Pending States & Optimistic UI
9 min read
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?
- We import
useNavigationfrom@remix-run/react. - We call the hook to get the current
navigationobject. - We create a boolean variable
isSubmittingfor readability. - In the
<button>, we use thedisabledattribute to prevent more clicks ifisSubmittingistrue. - 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.
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
isSubmittingis 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.
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?
- We use
useFetcher()to get afetcherobject. - We use
<fetcher.Form>instead of<Form>. This is crucial! - We check
fetcher.state(notnavigation.state) to disable the button. - The form posts to an
/subscribeaction route, but the user stays on the current page. fetcher.datawill hold the return value from your action. This is how we can show success or error messages without navigating.- We use a
useEffectto 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."
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?
- When the user clicks the "Like" button, the
<fetcher.Form>submits. - During this submission,
fetcher.formDatais no longernull. It contains the data being sent (postIdand the button'sintent). - Our
if (fetcher.formData)block immediately runs. We create anoptimisticLikesvariable that is one greater than the actual server state. - The component re-renders instantly, showing the new
optimisticLikescount and the "Liked" state before we've heard back from the server. - Once the server action completes, Remix revalidates the data, and the
post.likesprop 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. - If the server action had failed,
fetcher.formDatawould becomenullagain, the optimistic code would stop running, and the UI would revert to the originalpost.likescount.
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!
- Official Docs:
Happy coding! You're now equipped to build smoother and more delightful user experiences in Remix. π
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:
- Use
useFetcher: The component must use theuseFetcherhook to handle the form submission for liking/unliking. This will prevent a full page reload. - Form Submission: The
<fetcher.Form>should submit aPOSTrequest. It must include a hidden input withname="intent"and a value of either"like"or"unlike"based on the current liked status. - 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. - 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.formDatato predict the outcome of the action.
Expected result
Your final code should be a complete React component named LikeButton that correctly implements the following:
useFetcherHook: TheuseFetcherhook is initialized at the top of the component.- Optimistic State Calculation: Logic is in place to determine the optimistic
isLikedstatus andlikeCount. This logic inspectsfetcher.formDatato see if an action is in flight. Iffetcher.formDataexists, the optimistic state should be the opposite of the originalisLikedprop, and the count should be adjusted accordingly. - Pending State Management: A variable, for instance
isSubmitting, is derived fromfetcher.state === 'submitting'. This variable is used to disable the button and change its text during submission. fetcher.Form: The JSX contains a<fetcher.Form method="post">. Inside the form, there is:- A
<button>element with itsdisabledattribute set to theisSubmittingvariable. - The button's text dynamically changes based on
isSubmitting(e.g., from "Like" to "Liking..."). - A hidden
<input>withname="intent"and itsvaluedynamically set to"like"or"unlike".
- A
- The like count displayed on the page correctly reflects the optimistic value.