Home Web Front-end JS Tutorial Understanding React New Hooks

Understanding React New Hooks

Jan 07, 2025 pm 08:36 PM

Understanding React New Hooks

React 19 introduces several powerful new hooks that revolutionize how we handle forms and manage optimistic updates in our applications. In this blog, we'll explore useFormStatus, useActionState, and useOptimistic - three hooks that make our React applications more responsive and user-friendly.

useFormStatus: Enhanced Form Handling

The useFormStatus hook provides real-time information about form submissions, making it easier to create responsive and accessible forms. Let's explore how this hook improves upon React 18's form handling capabilities.

Example 1: Basic Form Loading State

function SubmitButton() {
  const { pending } = useFormStatus();

  return (
    <button disabled={pending}>
      {pending ? 'Submitting...' : 'Submit'}
    </button>
  );
}

function SignupForm() {
  return (
    <form action={async (formData) => {
      await submitSignupData(formData);
    }}>
      <input name="email" type="email" />
      <input name="password" type="password" />
      <SubmitButton />
    </form>
  );
}
Copy after login

In React 18, you'd need to manually manage loading states using useState. The new useFormStatus hook automatically handles this, reducing boilerplate code.

Example 2: Multiple Form States

function FormStatus() {
  const { pending, data, method } = useFormStatus();

  return (
    <div role="status">
      {pending && <span>Submitting via {method}...</span>}
      {!pending && data && <span>Last submission: {new Date().toLocaleString()}</span>}
    </div>
  );
}

function ContactForm() {
  return (
    <form action={async (formData) => {
      await submitContactForm(formData);
    }}>
      <textarea name="message" />
      <FormStatus />
      <SubmitButton />
    </form>
  );
}
Copy after login

Example 3: Form Validation Status

function ValidationStatus() {
  const { pending, validationErrors } = useFormStatus();

  return (
    <div role="alert">
      {validationErrors?.map((error, index) => (
        <p key={index} className="error">{error}</p>
      ))}
    </div>
  );
}

function RegistrationForm() {
  return (
    <form action={async (formData) => {
      const errors = validateRegistration(formData);
      if (errors.length) throw errors;
      await register(formData);
    }}>
      <input name="username" />
      <input name="email" type="email" />
      <ValidationStatus />
      <SubmitButton />
    </form>
  );
}
Copy after login

Example 4: Multi-Step Form Progress

function FormProgress() {
  const { pending, step, totalSteps } = useFormStatus();

  return (
    <div className="progress-bar">
      <div 
        className="progress" 
       >



<h3>
  
  
  Example 5: File Upload Progress
</h3>



<pre class="brush:php;toolbar:false">function UploadProgress() {
  const { pending, progress } = useFormStatus();

  return (
    <div>
      {pending && progress && (
        <div className="upload-progress">
          <div 
            className="progress-bar" 
           >



<h2>
  
  
  useActionState: Managing Action Results
</h2>

<p>The useActionState hook provides a way to track the state of form actions and server mutations, making it easier to handle success and error states.</p>

<h3>
  
  
  Example 1: Basic Action State
</h3>



<pre class="brush:php;toolbar:false">function SubmissionStatus() {
  const state = useActionState();

  return (
    <div>
      {state.status === 'success' && <p>Submission successful!</p>}
      {state.status === 'error' && <p>Error: {state.error.message}</p>}
    </div>
  );
}

function CommentForm() {
  return (
    <form action={async (formData) => {
      await submitComment(formData);
    }}>
      <textarea name="comment" />
      <SubmissionStatus />
      <SubmitButton />
    </form>
  );
}
Copy after login

Example 2: Action History

function ActionHistory() {
  const state = useActionState();

  return (
    <div>
      <h3>Recent Actions</h3>
      <ul>
        {state.history.map((action, index) => (
          <li key={index}>
            {action.type} - {action.timestamp}
            {action.status === 'error' && ` (Failed: ${action.error.message})`}
          </li>
        ))}
      </ul>
    </div>
  );
}
Copy after login

Example 3: Retry Mechanism

function RetryableAction() {
  const state = useActionState();

  return (
    <div>
      {state.status === 'error' && (
        <button 
          onClick={() => state.retry()}
          disabled={state.retrying}
        >
          {state.retrying ? 'Retrying...' : 'Retry'}
        </button>
      )}
    </div>
  );
}
Copy after login

Example 4: Action Queue

function ActionQueue() {
  const state = useActionState();

  return (
    <div>
      <h3>Pending Actions</h3>
      {state.queue.map((action, index) => (
        <div key={index}>
          {action.type} - Queued at {action.queuedAt}
          <button onClick={() => action.cancel()}>Cancel</button>
        </div>
      ))}
    </div>
  );
}
Copy after login

Example 5: Action Statistics

function ActionStats() {
  const state = useActionState();

  return (
    <div>
      <h3>Action Statistics</h3>
      <p>Success Rate: {state.stats.successRate}%</p>
      <p>Average Duration: {state.stats.avgDuration}ms</p>
      <p>Total Actions: {state.stats.total}</p>
    </div>
  );
}
Copy after login

useOptimistic: Smooth UI Updates

The useOptimistic hook enables immediate UI updates while waiting for server responses, creating a more responsive user experience.

Example 1: Optimistic Todo List

function TodoList() {
  const [todos, setTodos] = useState([]);
  const [optimisticTodos, addOptimisticTodo] = useOptimistic(
    todos,
    (state, newTodo) => [...state, newTodo]
  );

  async function addTodo(formData) {
    const newTodo = {
      id: Date.now(),
      text: formData.get('todo'),
      completed: false
    };

    addOptimisticTodo(newTodo);
    await saveTodo(newTodo);
  }

  return (
    <div>
      <form action={addTodo}>
        <input name="todo" />
        <button type="submit">Add Todo</button>
      </form>
      <ul>
        {optimisticTodos.map(todo => (
          <li key={todo.id}>{todo.text}</li>
        ))}
      </ul>
    </div>
  );
}
Copy after login

Example 2: Optimistic Like Button

function LikeButton({ postId, initialLikes }) {
  const [likes, setLikes] = useState(initialLikes);
  const [optimisticLikes, addOptimisticLike] = useOptimistic(
    likes,
    (state) => state + 1
  );

  async function handleLike() {
    addOptimisticLike();
    await likePost(postId);
  }

  return (
    <button onClick={handleLike}>
      {optimisticLikes} Likes
    </button>
  );
}
Copy after login

Example 3: Optimistic Comment Thread

function CommentThread({ postId }) {
  const [comments, setComments] = useState([]);
  const [optimisticComments, addOptimisticComment] = useOptimistic(
    comments,
    (state, newComment) => [...state, newComment]
  );

  async function submitComment(formData) {
    const comment = {
      id: Date.now(),
      text: formData.get('comment'),
      pending: true
    };

    addOptimisticComment(comment);
    await saveComment(postId, comment);
  }

  return (
    <div>
      <form action={submitComment}>
        <textarea name="comment" />
        <button type="submit">Comment</button>
      </form>
      {optimisticComments.map(comment => (
        <div key={comment.id}>



<h3>
  
  
  Example 4: Optimistic Shopping Cart
</h3>



<pre class="brush:php;toolbar:false">function ShoppingCart() {
  const [cart, setCart] = useState([]);
  const [optimisticCart, updateOptimisticCart] = useOptimistic(
    cart,
    (state, update) => {
      const { type, item } = update;
      switch (type) {
        case 'add':
          return [...state, item];
        case 'remove':
          return state.filter(i => i.id !== item.id);
        case 'update':
          return state.map(i => i.id === item.id ? item : i);
        default:
          return state;
      }
    }
  );

  async function updateCart(type, item) {
    updateOptimisticCart({ type, item });
    await saveCart({ type, item });
  }

  return (
    <div>
      {optimisticCart.map(item => (
        <div key={item.id}>
          {item.name} - ${item.price}
          <button onClick={() => updateCart('remove', item)}>Remove</button>
        </div>
      ))}
    </div>
  );
}
Copy after login

Example 5: Optimistic User Settings

function UserSettings() {
  const [settings, setSettings] = useState({});
  const [optimisticSettings, updateOptimisticSetting] = useOptimistic(
    settings,
    (state, update) => ({
      ...state,
      [update.key]: update.value
    })
  );

  async function updateSetting(key, value) {
    updateOptimisticSetting({ key, value });
    await saveSettings({ [key]: value });
  }

  return (
    <div>
      <div>
        <label>
          Theme:
          <select 
            value={optimisticSettings.theme} 
            onChange={e => updateSetting('theme', e.target.value)}
          >
            <option value="light">Light</option>
            <option value="dark">Dark</option>
          </select>
        </label>
      </div>
      <div>
        <label>
          Notifications:
          <input 
            type="checkbox"
            checked={optimisticSettings.notifications}
            onChange={e => updateSetting('notifications', e.target.checked)}
          />
        </label>
      </div>
    </div>
  );
}
Copy after login

Remember to check the official React documentation for the most up-to-date information and best practices when using these hooks in your applications.

Happy Coding!

The above is the detailed content of Understanding React New Hooks. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1664
14
PHP Tutorial
1266
29
C# Tutorial
1239
24
Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

The Evolution of JavaScript: Current Trends and Future Prospects The Evolution of JavaScript: Current Trends and Future Prospects Apr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript Engines: Comparing Implementations JavaScript Engines: Comparing Implementations Apr 13, 2025 am 12:05 AM

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

JavaScript: Exploring the Versatility of a Web Language JavaScript: Exploring the Versatility of a Web Language Apr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) How to Build a Multi-Tenant SaaS Application with Next.js (Frontend Integration) Apr 11, 2025 am 08:22 AM

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

From C/C   to JavaScript: How It All Works From C/C to JavaScript: How It All Works Apr 14, 2025 am 12:05 AM

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Building a Multi-Tenant SaaS Application with Next.js (Backend Integration) Apr 11, 2025 am 08:23 AM

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

See all articles