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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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

1

2

3

4

5

6

7

8

9

10

11

12

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

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

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

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.

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

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.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Zustand asynchronous operation: How to ensure the latest state obtained by useStore? Apr 04, 2025 pm 02:09 PM

Data update problems in zustand asynchronous operations. When using the zustand state management library, you often encounter the problem of data updates that cause asynchronous operations to be untimely. �...

See all articles