React 19 is now stable! New Hooks

React 19 is now stable! New Hooks

useTransition

Previously, managing response statuses such as idle, pending, success, and fail required maintaining a dedicated state. However, with React 19, this is no longer necessary as React handles these states internally. To leverage this improvement, we can use the useTransition hook.

Definition of useTransition

Parameters

No parameters

Returns

Returns an array with the below two items.

  • isPending - Keep the status of the transition.
  • startTransition - Transition function that invoke the API request.

Before introduce the useTransition hook, we have to maintain the response manually. Let's understand this with the below example.

Before use useTransition hook

Here we are manually maintaining the API request status manually in the isPending state. Before we invoke the updateName function, we change the isPending state to true and once we get the response from the async function we are changing isPending state to false.

But we can easily manage the same procedure by using useTransition like the below. React 19 will update the pending status automatically for you.

After use useTransition hook

When the async function is called, the transition immediately updates the isPending state to true, indicating that the operation is in progress. Once the async function completes and returns a response, the transition resets the isPending state to false, signalling that the operation has finished.

startTransition

The startTransition function is one of a returned value of useTransition hook. It let's you to update the transition.

Parameters

  • action - A function that updates some state by calling one or more set functions. React calls action immediately with no parameters and marks all state updates scheduled synchronously during the action function call as Transitions. Any async calls that are awaited in the action will be included in the Transition, but currently require wrapping any set functions after the await in an additional startTransition. State updates marked as Transitions will be non-blocking and will not display unwanted loading indicators.

The function passed to startTransition is called an "Action". By convention, any callback called inside startTransition (such as a callback prop) should be named action or include the "Action" suffix.

Returns

startTransition does not return anything.

Additionally you can invoke multiple actions in nested startTransaction actions like the below.

Invoking multiple actions

The function passed to startTransition is called the "Action". You can update state and (optionally) perform side effects within an Action, and the work will be done in the background without blocking user interactions on the page. A Transition can include multiple Actions, and while a Transition is in progress, your UI stays responsive.

To give the user feedback about in-progress Transitions, to isPending state switches to true at the first call to startTransition, and stays true until all Actions complete and the final state is shown to the user.

useActionState

React 19 introduces new hook called useActionState that allows us to update state based on the result of a form action. This make the common cases easier for Actions.

This will invoke at the top level of our component to create component state that is updated when a form action is invoked.

Definition of useActionState

Parameters

  • fn - The function to be called when the form is submitted or the submit button pressed. When the function is called, it will receive the previous state of the form (initially the initialState that you pass, subsequently its previous return value) as its initial argument, followed by the arguments that a form action normally receives.
  • initialState - The value you want the state to be initially. It can be any serialisable value. This argument is ignored after the action is first invoked.
  • permalink - This is a optional parameter. If "fn" is a server function and the form is submitted before the JavaScript bundle loads, the browser will navigate to the specified permalink URL, rather than the current page’s URL. Once the form has been hydrated, this parameter has no effect.

Returns

Returns an array with the below values.

  • state - This is the updated current state. Initially this will be the initial state.
  • formAction - The action we need to pass to the form component or the submit action for the form.
  • isPending - status of the function.

Common usage

Let's simplify this like the below.

Simple example

useActionState was previously called ReactDOM.useFormState in the Canary releases, but in version 19 "useFormState" is deprecated.

useFormStatus

This hook gives the status information of the last form submission. It's common to write design components that need access to information about the <form> they're in, without drilling props down to the component.

We can achieve this behavior through the Context API as well.

Definition of useFormStatus

Parameters

No parameters

Returns

Returns an object with the below properties.

  • pending - A boolean. If true, this means the parent <form> is pending submission. Otherwise, false.
  • data - An object implementing the FormData interface that contains the data the parent <form> is submitting. If there is no active submission or no parent <form>, it will be null.
  • method - A string value of either 'get' or 'post'. This represents whether the parent <form> is submitting with either a GET or POST HTTP method. By default, a <form> will use the GET method and can be specified by the method property.
  • action - A reference to the function passed to the action prop on the parent <form>. If there is no parent <form>, the property is null. If there is a URI value provided to the action prop, or no action prop specified, status.action will be null.

Usage of useFormStatus

useOptimistic

useOptimistic is a React Hook that lets you show a different state while an async action is underway. It accepts some state as an argument and returns a copy of that state that can be different during the duration of an async action such as a network request. You provide a function that takes the current state and the input to the action, and returns the optimistic state to be used while the action is pending.

Definition of useOptimistic

Parameters

  • state - The value to be returned initially and whenever no action is pending.
  • updateFn(currentState, optimisticValue) - A function that takes the current state and the optimistic value passed to addOptimistic and returns the resulting optimistic state. It must be a pure function. updateFn takes in two parameters. The currentState and the optimisticValue. The return value will be the merged value of the currentState and optimisticValue.

Returns

Returns an array with the below values.

  • optimisticState - The resulting optimistic state. It is equal to state unless an action is pending, in which case it is equal to the value returned by updateFn.
  • addOptimistic - addOptimistic is the dispatching function to call when you have an optimistic update. It takes one argument, optimisticValue, of any type and will call the updateFn with state and optimisticValue.

Usage of useOptimistic


Shashith Sandunil

Software Engineer

2 个月

Useful tips

回复

要查看或添加评论,请登录

Hemantha Wijegunarathna的更多文章

  • JavaScript Function Context Utilities

    JavaScript Function Context Utilities

    Context Binding: Managing what this refers to (e.g.

    1 条评论
  • JavaScript Closure

    JavaScript Closure

    A closure is a feature in JavaScript (and many other programming languages) where a function "remembers" the variables…

  • TypeScript Duck-Typing

    TypeScript Duck-Typing

    Duck typing in TypeScript is a concept where the compatibility between types is determined by their structure or shape…

  • AWS CDK Stack

    AWS CDK Stack

    AWS CDK Stack refers to a fundamental unit of deployment in the AWS Cloud Development Kit (CDK), an…

  • React "use" API

    React "use" API

    The “use” React API is a relatively new feature that allows React components to handle asynchronous operations directly…

  • Difference between .ts and .d.ts files

    Difference between .ts and .d.ts files

    .ts file contains the actual executable code including implementations, functions, classes, and logic along with the…

    1 条评论

社区洞察

其他会员也浏览了