You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Commit 5ffda45
Browse filesBrowse the repository at this point in the historyBrowse files
Copy file name to clipboardExpand all lines: src/content/reference/react/useOptimistic.md
+35-35Lines changed: 35 additions & 35 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -337,45 +337,45 @@ export async function submitForm() {
337
337
338
338
</Sandpack>
339
339
340
-
When the button is clicked, `setIsPending(true)`uses optimistic state to immediately show "Submitting..." and disable the button. When the Action is done, `isPending`is rendered as`false`automatically.
340
+
Quando o botão é clicado, `setIsPending(true)`usa o estado otimista para mostrar imediatamente "Submitting..." e desabilitar o botão. Quando a Ação termina, `isPending`é renderizado como`false`automaticamente.
341
341
342
-
This pattern automatically shows a pending state however `action`prop is used with`Button`:
342
+
Esse padrão mostra automaticamente um estado pendente, não importa como a prop `action`seja usada com`Button`:
343
343
344
344
```js
345
-
//Show pending state for a state update
345
+
//Mostra o state pendente para uma atualização de state
//Mostra o state pendente para qualquer combinação
355
355
<Button action={async () => {
356
356
setState(c=> c +1);
357
357
awaitfetch(/* ... */);
358
358
navigate('/done');
359
359
}} />
360
360
```
361
361
362
-
The pending state will be shown until everything in the `action`prop is finished.
362
+
O estado pendente vai ser exibido até que tudo na prop `action`termine.
363
363
364
364
<Note>
365
365
366
-
You can also use [`useTransition`](/reference/react/useTransition) to get pending state via `isPending`.
366
+
Você também pode usar [`useTransition`](/reference/react/useTransition) para obter o estado pendente via `isPending`.
367
367
368
-
The difference is that`useTransition`gives you the`startTransition` function, while`useOptimistic`works with any Transition. Use whichever fits your component's needs.
368
+
A diferença é que`useTransition`fornece a função`startTransition`, enquanto`useOptimistic`funciona com qualquer Transição. Use o que fizer mais sentido para o seu componente.
369
369
370
370
</Note>
371
371
372
372
---
373
373
374
-
### Updating props or state optimistically {/*updating-props-or-state-optimistically*/}
374
+
### Atualizando props ou estado de forma otimista {/*updating-props-or-state-optimistically*/}
375
375
376
-
You can wrap props or state in`useOptimistic`to update it immediately while an Action is in progress.
376
+
Você pode envolver props ou estado em`useOptimistic`para atualizá-los imediatamente enquanto uma Ação está em andamento.
377
377
378
-
In this example, `LikeButton`receives`isLiked`as a prop and immediately toggles it when clicked:
378
+
Neste exemplo, `LikeButton`recebe`isLiked`como prop e o alterna imediatamente quando clicado:
379
379
380
380
<Sandpack>
381
381
@@ -420,7 +420,7 @@ export default function App() {
//Not using StrictMode so double render logs are not shown.
435
+
//Sem StrictMode, para que os logs da renderização dupla não apareçam.
436
436
root.render(<App />);
437
437
```
438
438
439
439
</Sandpack>
440
440
441
-
When the button is clicked, `setOptimisticIsLiked`immediately updates the displayed state to show the heart as liked. Meanwhile, `await toggleLike`runs in the background. When the`await`completes, `setIsLiked`parent updates the "real" `isLiked`state, and the optimistic state is rendered to match this new value.
441
+
Quando o botão é clicado, `setOptimisticIsLiked`atualiza imediatamente o estado exibido para mostrar o coração como curtido. Enquanto isso, `await toggleLike`é executado em segundo plano. Quando o`await`termina, o `setIsLiked`do componente pai atualiza o estado `isLiked`"real", e o estado otimista é renderizado de acordo com esse novo valor.
442
442
443
443
<Note>
444
444
445
-
This example reads from `optimisticIsLiked`to calculate the next value. This works when the base state won't change, but if the base state might change while your Action is pending, you may want to use a state updater or the reducer.
445
+
Este exemplo lê `optimisticIsLiked`para calcular o próximo valor. Isso funciona quando o estado base não vai mudar, mas, se o estado base puder mudar enquanto a sua Ação está pendente, talvez seja melhor usar uma função atualizadora ou o reducer.
446
446
447
-
See [Updating state based on the current state](#updating-state-based-on-current-state) for an example.
447
+
Veja [Atualizando o estado com base no estado atual](#updating-state-based-on-current-state) para um exemplo.
448
448
449
449
</Note>
450
450
451
451
---
452
452
453
-
### Updating multiple values together {/*updating-multiple-values-together*/}
453
+
### Atualizando vários valores juntos {/*updating-multiple-values-together*/}
454
454
455
-
When an optimistic update affects multiple related values, use a reducer to update them together. This ensures the UI stays consistent.
455
+
Quando uma atualização otimista afeta vários valores relacionados, use um reducer para atualizá-los juntos. Isso garante que a UI permaneça consistente.
456
456
457
-
Here's a follow button that updates both the follow state and follower count:
457
+
Aqui está um botão de seguir que atualiza tanto o estado de seguir quanto a contagem de seguidores:
458
458
459
459
<Sandpack>
460
460
@@ -533,48 +533,48 @@ export async function unfollowUser(name) {
533
533
534
534
</Sandpack>
535
535
536
-
The reducer receives the new `isFollowing`value and calculates both the new follow state and the updated follower count in a single update. This ensures the button text and count always stay in sync.
536
+
O reducer recebe o novo valor de `isFollowing`e calcula tanto o novo estado de seguir quanto a contagem de seguidores atualizada em uma única atualização. Isso garante que o texto do botão e a contagem fiquem sempre sincronizados.
537
537
538
538
539
539
<DeepDive>
540
540
541
-
#### Choosing between updaters and reducers {/*choosing-between-updaters-and-reducers*/}
541
+
#### Escolhendo entre funções atualizadoras e reducers {/*choosing-between-updaters-and-reducers*/}
542
542
543
-
`useOptimistic`supports two patterns for calculating state based on current state:
543
+
`useOptimistic`suporta dois padrões para calcular o estado com base no estado atual:
544
544
545
-
**Updater functions** work like [useState updaters](/reference/react/useState#updating-state-based-on-the-previous-state). Pass a function to the setter:
545
+
**Funções atualizadoras** funcionam como as [funções atualizadoras do useState](/reference/react/useState#updating-state-based-on-the-previous-state). Passe uma função para o setter:
//Calculate next state based on current and action
556
+
//Calcula o próximo state com base no state atual e na action
557
557
});
558
558
dispatch(action);
559
559
```
560
560
561
-
**Use updaters** for calculations where the setter call naturally describes the update. This is similar to using `setState(prev=>...)`with`useState`.
561
+
**Use funções atualizadoras** para cálculos em que a chamada do setter descreve naturalmente a atualização. É parecido com usar `setState(prev=>...)`com`useState`.
562
562
563
-
**Use reducers** when you need to pass data to the update (like which item to add) or when handling multiple types of updates with a single hook.
563
+
**Use reducers** quando precisar passar dados para a atualização (como qual item adicionar) ou quando tratar vários tipos de atualização com um único Hook.
564
564
565
-
**Why use a reducer?**
565
+
**Por que usar um reducer?**
566
566
567
-
Reducers are essential when the base state might change while your Transition is pending. If`todos`changes while your add is pending (for example, another user added a todo), React will re-run your reducer with the new `todos`to recalculate what to show. This ensures your new todo is added to the latest list, not an outdated copy.
567
+
Reducers são essenciais quando o estado base pode mudar enquanto a sua Transição está pendente. Se`todos`mudar enquanto a sua adição está pendente (por exemplo, outro usuário adicionou um todo), o React vai executar o seu reducer de novo com o novo `todos`para recalcular o que mostrar. Isso garante que o seu novo todo seja adicionado à lista mais recente, e não a uma cópia desatualizada.
568
568
569
-
An updater function like`setOptimistic(prev=> [...prev, newItem])`would only see the state from when the Transition started, missing any updates that happened during the async work.
569
+
Uma função atualizadora como`setOptimistic(prev=> [...prev, newItem])`só veria o estado do momento em que a Transição começou, perdendo quaisquer atualizações que tenham acontecido durante o trabalho assíncrono.
570
570
571
571
</DeepDive>
572
572
573
573
---
574
574
575
-
### Optimistically adding to a list {/*optimistically-adding-to-a-list*/}
575
+
### Adicionando itens a uma lista de forma otimista {/*optimistically-adding-to-a-list*/}
576
576
577
-
When you need to optimistically add items to a list, use a`reducer`:
577
+
Quando você precisar adicionar itens a uma lista de forma otimista, use um`reducer`:
0 commit comments