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
`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.
23
+
Хук `useOptimistic`дає змогу відображати особливий стан протягом виконання асинхронної дії. Він приймає певний стан як аргумент і повертає копію цього стану, яка може відрізнятися від переданого стану протягом виконання асинхронної дії, наприклад, мережевого запиту. Ви описуєте функцію, яка отримує поточний стан і вхідні дані для дії, та повертає «оптимістичний» стан, який буде відображатися, поки дія триває.
24
24
25
-
This state is called the "optimistic" state because it is usually used to immediately present the user with the result of performing an action, even though the action actually takes time to complete.
25
+
Цей стан називається «оптимістичним», тому що зазвичай використовується, щоб показати користувачеві очікуваний результат одразу, навіть якщо на завершення дії потрібен певний час.
26
26
27
27
```js
28
28
import { useOptimistic } from'react';
@@ -32,35 +32,35 @@ function AppContainer() {
32
32
state,
33
33
// updateFn
34
34
(currentState, optimisticValue) => {
35
-
//merge and return new state
36
-
//with optimistic value
35
+
//об’єднайте і поверніть новий стан
36
+
//з оптимістичним значенням
37
37
}
38
38
);
39
39
}
40
40
```
41
41
42
-
[See more examples below.](#usage)
42
+
[Перегляньте більше прикладів нижче.](#usage)
43
43
44
-
#### Parameters {/*parameters*/}
44
+
#### Параметри {/*parameters*/}
45
45
46
-
*`state`: the value to be returned initially and whenever no action is pending.
47
-
*`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`.
46
+
*`state`: значення, яке повертається перший раз та кожного разу, коли немає дії, що виконується.
47
+
*`updateFn(currentState, optimisticValue)`: функція, яка приймає поточний стан і оптимістичне значення, передане до `addOptimistic`, та повертає розрахований оптимістичний стан. Повинна бути чистою функцією. `updateFn`приймає два параметри: `currentState`і `optimisticValue`. Функція повертає значення, що об'єднує `currentState`і`optimisticValue`.
48
48
49
49
50
-
#### Returns {/*returns*/}
50
+
#### Результат {/*returns*/}
51
51
52
-
*`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`.
53
-
*`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`.
52
+
*`optimisticState`: розрахований оптимістичний стан. Він дорівнює `state`допоки немає дії, що виконується, інакше він дорівнює значенню, яке повертає`updateFn`.
53
+
*`addOptimistic`: `addOptimistic`— це функція, яку потрібно викликати для оптимістичного оновлення. Вона приймає один аргумент`optimisticValue` будь-якого типу та викликає `updateFn`із`state`і`optimisticValue`.
54
54
55
55
---
56
56
57
-
## Usage {/*usage*/}
57
+
## Використання {/*usage*/}
58
58
59
-
### Optimistically updating forms {/*optimistically-updating-with-forms*/}
59
+
### Оптимістичне оновлення форм {/*optimistically-updating-with-forms*/}
60
60
61
-
The`useOptimistic`Hook provides a way to optimistically update the user interface before a background operation, like a network request, completes. In the context of forms, this technique helps to make apps feel more responsive. When a user submits a form, instead of waiting for the server's response to reflect the changes, the interface is immediately updated with the expected outcome.
61
+
Хук`useOptimistic`дає змогу оптимістично оновлювати інтерфейс доки завершиться фонова операція, наприклад мережевий запит. У контексті форм такий підхід створює відчуття швидшої реакції застосунків. Коли користувач надсилає форму, замість очікування відповіді від сервера, інтерфейс одразу оновлюється і відображає очікуваний результат.
62
62
63
-
For example, when a user types a message into the form and hits the "Send" button, the`useOptimistic`Hook allows the message to immediately appear in the list with a "Sending..." label, even before the message is actually sent to a server. This "optimistic" approach gives the impression of speed and responsiveness. The form then attempts to truly send the message in the background. Once the server confirms the message has been received, the "Sending..." label is removed.
63
+
Наприклад, коли користувач вводить повідомлення у форму й натискає кнопку «Надіслати», хук`useOptimistic`дозволяє одразу відобразити це повідомлення у списку з позначкою «Надсилання...», ще до того, як воно реально буде відправлене на сервер. Такий «оптимістичний» підхід створює відчуття швидкої роботи застосунку. Після цього форма справді намагається надіслати повідомлення у фоновому режимі. Коли сервер підтвердить, що повідомлення було отримано, позначка «Надсилання...» зникне.
64
64
65
65
<Sandpack>
66
66
@@ -92,13 +92,13 @@ function Thread({ messages, sendMessageAction }) {
0 commit comments