Başvuru dokümanı

useTransition()

Bazı state güncellemelerini transition (ertelenen güncelleme) olarak işaretlemek için, bileşeninizin en üst seviyesinde useTransition’ı çağırın.

Parametreler

useTransition parametre almaz.

Dönen değerler

useTransition, tam olarak iki elemanlı dizi döndürür:

  1. The isPending flag that tells you whether there is a pending Transition.
  2. The that lets you mark updates as a Transition.

startTransition(action)

The startTransition function returned by useTransition lets you mark an update as a Transition.

Parameters

  • action: A function that updates some state by calling one or more . 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 (see ). State updates marked as Transitions will be and .

Dönen değerler

startTransition herhangi bir şey geri döndürmez.

Uyarılar

  • useTransition bir Hook olduğu için yalnızca bileşenlerin içinde veya özel Hook’ların içinde çağrılabilir. Eğer bir transition işlemini başka bir yerden başlatmanız gerekiyorsa (örneğin, bir veri kütüphanesinden), bunun yerine bağımsız ’ı çağırın.

  • Bir güncellemeyi transition olarak kullanmak için, ilgili state’in set fonksiyonuna erişebilmeniz gerekiyor. Eğer bir prop veya özel bir Hook dönüş değerine yanıt olarak transition başlatmak isterseniz, bunun yerine özelliğini kullanmayı deneyebilirsiniz.

  • The function you pass to startTransition is called immediately, marking all state updates that happen while it executes as Transitions. If you try to perform state updates in a setTimeout, for example, they won’t be marked as Transitions.

  • You must wrap any state updates after any async requests in another startTransition to mark them as Transitions. This is a known limitation that we will fix in the future (see ).

  • The startTransition function has a stable identity, so you will often see it omitted from Effect dependencies, but including it will not cause the Effect to fire. If the linter lets you omit a dependency without errors, it is safe to do.

  • Bir state güncelleme işlemi transition olarak işaretlendiğinde, diğer güncelleme işlemleri bu işlemi kesintiye uğratabilir. Örneğin, bir grafik bileşenini güncelleyen transition işlemi sırasında, grafik bileşeni tekrar render işlemi devam ederken bir giriş alanına yazmaya başlarsanız, React, giriş alanındaki güncellemeyi işledikten sonra tekrar render işlemini başlatır.

  • Transition güncellemeleri, metin girişlerini kontrol etmek için kullanılamaz.

  • If there are multiple ongoing Transitions, React currently batches them together. This is a limitation that may be removed in a future release.

Kullanım

Perform non-blocking updates with Actions

Call useTransition at the top of your component to create Actions, and access the pending state:

useTransition, tam olarak iki elemanlı dizi döndürür:

  1. The isPending flag that tells you whether there is a pending Transition.
  2. The startTransition function that lets you create an Action.

To start a Transition, pass a function to startTransition like this:

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. For example, if the user clicks a tab but then changes their mind and clicks another tab, the second click will be immediately handled without waiting for the first update to finish.

To give the user feedback about in-progress Transitions, the 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. Transitions ensure side effects in Actions to complete in order to , and you can provide immediate feedback while the Transition is in progress with useOptimistic.


Exposing action prop from components

You can expose an action prop from a component to allow a parent to call an Action.

For example, this TabButton component wraps its onClick logic in an action prop:

Because the parent component updates its state inside the action, that state update gets marked as a Transition. This means you can click on “Posts” and then immediately click “Contact” and it does not block user interactions:


Displaying a pending visual state

useTransition tarafından döndürülen isPending boolean değerini kullanarak, bir transition işleminin hala devam ettiğini kullanıcıya gösterebilirsiniz. Örneğin, sekme düğmesi özel bir “pending” (beklemede) görsel state’ine sahip olabilir:

“Posts”a tıkladığınızda, sekme düğmesinin anında güncellenmesi sebebiyle daha hızlı bir yanıt verdiğini göreceksiniz:


İstenmeyen yükleme göstergelerinin engellenmesi

In this example, the PostsTab component fetches some data using . When you click the “Posts” tab, the PostsTab component suspends, causing the closest loading fallback to appear:

Hiding the entire tab container to show a loading indicator leads to a jarring user experience. If you add useTransition to TabButton, you can instead display the pending state in the tab button instead.

Artık “Posts”a tıklamanın tüm sekme konteynırını bir döndürücüyle (spinner) değiştirmediğini fark edeceksiniz:


Suspense özelliği etkinleştirilmiş yönlendirici oluşturma

Eğer bir React framework’ü veya yönlendirici oluşturuyorsanız, sayfa gezinmelerini transition’lar olarak işaretlemenizi öneririz.

This is recommended for three reasons:

  • which lets the user click away without waiting for the re-render to complete.
  • which lets the user avoid jarring jumps on navigation.
  • which lets the user wait for side effects to complete before the new page is shown.

Here is a simplified router example using Transitions for navigations.


Bir hata sınırı ile kullanıcılara bir hatayı gösterme

If a function passed to startTransition throws an error, you can display an error to your user with an . To use an error boundary, wrap the component where you are calling the useTransition in an error boundary. Once the function passed to startTransition errors, the fallback for the error boundary will be displayed.


Sorun Giderme

Transition içinde bir inputu (girdiyi) güncelleme işlemi çalışmaz

Bir input alanını kontrol eden state değişkeni için transition kullanamazsınız:

Bunun nedeni, transition işlemlerinin bloklamayan bir yapıda olmalarıdır, ancak bir değişiklik olayına yanıt olarak input alanını güncellemek eşzamanlı olarak gerçekleşmelidir. Yazma işlemine yanıt olarak transition çalıştırmak isterseniz, iki seçeneğiniz vardır:

  1. İki ayrı state değişkeni tanımlayabilirsiniz: biri input state’i için (her zaman eşzamanlı olarak güncellenir), diğeri de bir transition güncelleyeceğiniz değişken. Bu şekilde, girişi eşzamanlı state kullanarak kontrol etmenizi ve transition state değişkenini (girişin “gerisinde kalacak” olan) render işleminize aktarmanızı sağlar.
  2. Alternatif olarak, bir state değişkeniniz olabilir ve gerçek değerin “gerisinde kalacak” olan ekleyebilirsiniz. Bu, yeni değeri otomatik olarak “yakalamak” için bloklamayan yeniden render işlemini tetikler.

React, state güncellememi bir transition olarak işlemiyor

State güncellemesini bir transition içine aldığınızda, bunun startTransition çağrısı esnasında gerçekleştiğinden emin olun:

The function you pass to startTransition must be synchronous. You can’t mark an update as a Transition like this:

Onun yerine, bunu yapabilirsiniz:


React doesn’t treat my state update after await as a Transition

When you use await inside a startTransition function, the state updates that happen after the await are not marked as Transitions. You must wrap state updates after each await in a startTransition call:

Ancak, aşağıdaki şekilde işe yarar:

This is a JavaScript limitation due to React losing the scope of the async context. In the future, when is available, this limitation will be removed.


Bileşenin dışından useTransition’u çağırmak istiyorum

useTransition, bir Hook olduğu için bileşenin dışından çağrılamaz. Bu durumlarda, adlı bağımsız bir metod kullanabilirsiniz. Bu yöntem aynı şekilde çalışır, ancak isPending belirteçini sağlamaz.


startTransition’a ilettiğim fonksiyon hemen çalışıyor

Bu kodu çalıştırırsanız, 1, 2, 3 yazdırır:

1, 2, 3 yazdırması beklenir. startTransition’a ilettiğiniz fonksiyon gecikmez. Tarayıcının setTimeout metodu aksine, callback’i daha sonra çalıştırmaz. React, fonksiyonunuzu hemen çalıştırır, ancak çalışırken planlanan herhangi bir state güncellemesi transition olarak işaretlenir. Bunu nasıl çalıştığını aşağıdaki gibi düşünebilirsiniz:

My state updates in Transitions are out of order

If you await inside startTransition, you might see the updates happen out of order.

In this example, the updateQuantity function simulates a request to the server to update the item’s quantity in the cart. This function artificially returns the every other request after the previous to simulate race conditions for network requests.

Try updating the quantity once, then update it quickly multiple times. You might see the incorrect total:

When clicking multiple times, it’s possible for previous requests to finish after later requests. When this happens, React currently has no way to know the intended order. This is because the updates are scheduled asynchronously, and React loses context of the order across the async boundary.

This is expected, because Actions within a Transition do not guarantee execution order. For common use cases, React provides higher-level abstractions like and that handle ordering for you. For advanced use cases, you’ll need to implement your own queuing and abort logic to handle this.

Example of useActionState handling execution order: