DEV Community

Cover image for New React 19 Hooks (With Examples)
Vivek Mengu
Vivek Mengu

Posted on

New React 19 Hooks (With Examples)

React 19 introduces several new hooks, which offer more refined control over asynchronous operations, form management, and optimistic UI updates. These hooks simplify common use cases in React apps by reducing boilerplate code and enhancing performance. Here are some of the key additions:

1. use()

The use() hook is a new way to handle asynchronous data in components, simplifying the consumption of promises. It works well with Suspense, allowing you to wait for a promise to resolve before rendering a component.

Use Case: Fetching data and showing it directly in the component without additional async handling.

Example: Fetching User Profile Data

import React, { use } from 'react';

async function fetchUserProfile(userId) {
    const response = await fetch(`/api/users/${userId}`);
    return response.json();
}

function UserProfile({ userId }) {
    const user = use(fetchUserProfile(userId)); // Directly use the async function

    return (
        <div>
            <h1>{user.name}</h1>
            <p>{user.bio}</p>
        </div>
    );
}

export default function App() {
    return (
        <React.Suspense fallback={<div>Loading...</div>}>
            <UserProfile userId="123" />
        </React.Suspense>
    );
}

Enter fullscreen mode Exit fullscreen mode

In this example, use() enables you to retrieve user data directly in the component, without additional async/await or .then() calls. Wrapping UserProfile in Suspense allows the component to show a loading state until data fetching is complete.


2. useOptimistic()

useOptimistic helps manage optimistic updates, where the UI updates immediately based on an expected change, while backend confirmation happens in the background. This can significantly enhance user experience by making interactions feel more responsive.

Use Case: Implementing a “Like” button where the UI reflects the like instantly, even if the server update is still pending.

Example: Optimistic “Like” Button

import React, { useOptimistic } from 'react';

function LikeButton({ postId }) {
    const [isLiked, setIsLiked] = useOptimistic(false);

    const handleLike = async () => {
        setIsLiked(true);  // Optimistic update
        await api.likePost(postId); // Simulated server call
    };

    return (
        <button onClick={handleLike}>
            {isLiked ? 'Liked' : 'Like'}
        </button>
    );
}

Enter fullscreen mode Exit fullscreen mode

In this example, setIsLiked(true) updates the button’s state immediately. The server call (api.likePost) then processes in the background. This approach allows the user to see instant feedback, with useOptimistic managing the optimistic state.


3. useFormStatus()

useFormStatus provides a way to monitor the status of form submission or validation, making it easier to display loading indicators, disable the submit button during submission, or show validation messages.

Use Case: Displaying a loading message and disabling the submit button while a form is being submitted.

Example: Form Submission with Loading Indicator

import React, { useFormStatus } from 'react';

function MyForm() {
    const { isSubmitting, isValid } = useFormStatus();

    return (
        <form action="/submit" method="post">
            <label>
                Name:
                <input type="text" name="name" required />
            </label>
            <button type="submit" disabled={isSubmitting || !isValid}>
                {isSubmitting ? 'Submitting...' : 'Submit'}
            </button>
        </form>
    );
}

Enter fullscreen mode Exit fullscreen mode

In this example, useFormStatus tracks if the form is currently submitting (isSubmitting) or if it’s valid (isValid). The submit button is disabled if the form is either submitting or invalid, providing visual feedback to the user during submission.


4. useFormState()

useFormState is designed to manage form state more seamlessly. This hook allows you to manage and track form values without needing to handle state manually, making complex form handling simpler and more declarative.

Use Case: Automatically managing state for multiple form fields in a contact form.

Example: Managing Form Values

import React, { useFormState } from 'react';

function ContactForm() {
    const { values, handleChange } = useFormState({
        name: '',
        email: '',
    });

    return (
        <form>
            <label>
                Name:
                <input
                    type="text"
                    name="name"
                    value={values.name}
                    onChange={handleChange}
                />
            </label>
            <label>
                Email:
                <input
                    type="email"
                    name="email"
                    value={values.email}
                    onChange={handleChange}
                />
            </label>
            <button type="submit">Submit</button>
        </form>
    );
}

Enter fullscreen mode Exit fullscreen mode

Here, useFormState automatically manages the state of name and email. handleChange updates the form values, making form management straightforward and reducing the need for boilerplate state handling.


Conclusion

React 19’s new hooks are a game-changer, making everyday tasks in web development faster, cleaner, and more intuitive. These additions simplify how we handle things like loading data, managing form states, and giving users responsive feedback.

With useOptimistic, you can make the interface feel more responsive by updating the UI instantly, even before the server confirms a user action. Imagine hitting a “like” button and immediately seeing it change state—this creates a seamless experience that feels real-time.

Form handling has also never been easier. useFormStatus and useFormState handle form submission status and input values, so you’re free from manually tracking each input field or handling tedious validation states. These hooks let you focus on your app’s logic instead of repetitive code.

React 19’s use hook streamlines data fetching, making it incredibly simple to load async data right in your component, with minimal code. It works hand-in-hand with Suspense to show a loading indicator until data is ready.

These hooks save time, reduce boilerplate code, and prioritise a smooth user experience, making it easier to create efficient, user-friendly interfaces. React 19 doesn’t just add tools it’s geared toward helping developers work smarter, build better apps, and give users the best experience possible.

Top comments (0)