Skip to content

Commit fc789a2

Browse files
committed
Translated first usage example of useDeferredValue
1 parent 62fd47e commit fc789a2

File tree

1 file changed

+28
-28
lines changed

1 file changed

+28
-28
lines changed

src/content/reference/react/useDeferredValue.md

Lines changed: 28 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -58,11 +58,11 @@ function SearchPage() {
5858

5959
---
6060

61-
## Usage {/*usage*/}
61+
## Использование {/*usage*/}
6262

63-
### Showing stale content while fresh content is loading {/*showing-stale-content-while-fresh-content-is-loading*/}
63+
### Отображение старых данных, пока загружаются новые {/*showing-stale-content-while-fresh-content-is-loading*/}
6464

65-
Call `useDeferredValue` at the top level of your component to defer updating some part of your UI.
65+
Чтобы отложить обновление для части UI, вызовите `useDeferredValue` на верхнем уровне своего компонента:
6666

6767
```js [[1, 5, "query"], [2, 5, "deferredQuery"]]
6868
import { useState, useDeferredValue } from 'react';
@@ -74,25 +74,25 @@ function SearchPage() {
7474
}
7575
```
7676

77-
During the initial render, the <CodeStep step={2}>deferred value</CodeStep> will be the same as the <CodeStep step={1}>value</CodeStep> you provided.
77+
При первом рендеринге <CodeStep step={2}>отложенное значение</CodeStep> будет равно <CodeStep step={1}>значению</CodeStep>, которое вы передадите.
7878

79-
During updates, the <CodeStep step={2}>deferred value</CodeStep> will "lag behind" the latest <CodeStep step={1}>value</CodeStep>. In particular, React will first re-render *without* updating the deferred value, and then try to re-render with the newly received value in background.
79+
В следующих обновлениях <CodeStep step={2}>отложенное значение</CodeStep> будет как бы "отставать" от актуального <CodeStep step={1}>значения</CodeStep>. А именно: сначала React отрендерит компонент, *не обновляя* отложенное значение, а затем в фоне попытается отрендерить компонент с новым значением.
8080

81-
**Let's walk through an example to see when this is useful.**
81+
**Разберём на примере, когда это может быть полезно.**
8282

8383
<Note>
8484

85-
This example assumes you use one of Suspense-enabled data sources:
85+
Предполагается, что данные в этом примере вы получаете через источники, которые поддерживают Suspense:
8686

87-
- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/advanced-features/react-18)
88-
- Lazy-loading component code with [`lazy`](/reference/react/lazy)
87+
- Запрашиваете данные с помощью поддерживающих Suspense фреймворков, как, например, [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) или [Next.js](https://nextjs.org/docs/advanced-features/react-18).
88+
- Лениво загружаете код компонентов с помощью [`lazy`](/reference/react/lazy).
8989

90-
[Learn more about Suspense and its limitations.](/reference/react/Suspense)
90+
[Подробнее о Suspense и связанных с ним ограничениях.](/reference/react/Suspense)
9191

9292
</Note>
9393

9494

95-
In this example, the `SearchResults` component [suspends](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading) while fetching the search results. Try typing `"a"`, waiting for the results, and then editing it to `"ab"`. The results for `"a"` get replaced by the loading fallback.
95+
В этом примере компонент `SearchResults` [задерживается](/reference/react/Suspense#displaying-a-fallback-while-content-is-loading), т.к. отправляет поисковый запрос. Попробуйте ввести `"a"`, дождаться результатов поиска, и затем ввести `"ab"`. На месте результатов по запросу `"a"` ненадолго появится индикатор загрузки.
9696

9797
<Sandpack>
9898

@@ -120,10 +120,10 @@ export default function App() {
120120
return (
121121
<>
122122
<label>
123-
Search albums:
123+
Найти альбом:
124124
<input value={query} onChange={e => setQuery(e.target.value)} />
125125
</label>
126-
<Suspense fallback={<h2>Loading...</h2>}>
126+
<Suspense fallback={<h2>Загрузка...</h2>}>
127127
<SearchResults query={query} />
128128
</Suspense>
129129
</>
@@ -146,7 +146,7 @@ export default function SearchResults({ query }) {
146146
}
147147
const albums = use(fetchData(`/search?q=${query}`));
148148
if (albums.length === 0) {
149-
return <p>No matches for <i>"{query}"</i></p>;
149+
return <p>По запросу <i>"{query}"</i> ничего не найдено</p>;
150150
}
151151
return (
152152
<ul>
@@ -284,7 +284,7 @@ input { margin: 10px; }
284284

285285
</Sandpack>
286286

287-
A common alternative UI pattern is to *defer* updating the list of results and to keep showing the previous results until the new results are ready. Call `useDeferredValue` to pass a deferred version of the query down:
287+
Однако здесь можно применить другой частый паттерн в UI: *отложить* обновление списка результатов, продолжив показывать старые результаты, пока не подготовятся новые. Чтобы передавать в результаты поиска отложенную версию запроса, можно применить `useDeferredValue`:
288288

289289
```js {3,11}
290290
export default function App() {
@@ -293,20 +293,20 @@ export default function App() {
293293
return (
294294
<>
295295
<label>
296-
Search albums:
296+
Найти альбом:
297297
<input value={query} onChange={e => setQuery(e.target.value)} />
298298
</label>
299-
<Suspense fallback={<h2>Loading...</h2>}>
299+
<Suspense fallback={<h2>Загрузка...</h2>}>
300300
<SearchResults query={deferredQuery} />
301301
</Suspense>
302302
</>
303303
);
304304
}
305305
```
306306

307-
The `query` will update immediately, so the input will display the new value. However, the `deferredQuery` will keep its previous value until the data has loaded, so `SearchResults` will show the stale results for a bit.
307+
Значение `query` будет всегда актуальным -- соответственно и отображаемый в поле ввода запрос. Но в `deferredQuery` будет предыдущее значение запроса, пока не загрузятся новые результаты поиска -- поэтому `SearchResults` ещё некоторое время будет показывать старые результаты.
308308

309-
Enter `"a"` in the example below, wait for the results to load, and then edit the input to `"ab"`. Notice how instead of the Suspense fallback, you now see the stale result list until the new results have loaded:
309+
В изменённом примере ниже введите `"a"`, дождитесь загрузки результатов поиска, и затем измените запрос на `"ab"`. Обратите внимание, что теперь, пока загружаются новые результаты, вместо индикатора загрузки (заглушки Suspense) отображаются предыдущие результаты.
310310

311311
<Sandpack>
312312

@@ -335,10 +335,10 @@ export default function App() {
335335
return (
336336
<>
337337
<label>
338-
Search albums:
338+
Найти альбом:
339339
<input value={query} onChange={e => setQuery(e.target.value)} />
340340
</label>
341-
<Suspense fallback={<h2>Loading...</h2>}>
341+
<Suspense fallback={<h2>Загрузка...</h2>}>
342342
<SearchResults query={deferredQuery} />
343343
</Suspense>
344344
</>
@@ -361,7 +361,7 @@ export default function SearchResults({ query }) {
361361
}
362362
const albums = use(fetchData(`/search?q=${query}`));
363363
if (albums.length === 0) {
364-
return <p>No matches for <i>"{query}"</i></p>;
364+
return <p>По запросу <i>"{query}"</i> ничего не найдено</p>;
365365
}
366366
return (
367367
<ul>
@@ -501,17 +501,17 @@ input { margin: 10px; }
501501

502502
<DeepDive>
503503

504-
#### How does deferring a value work under the hood? {/*how-does-deferring-a-value-work-under-the-hood*/}
504+
#### Как работает отложенное обновление значения? {/*how-does-deferring-a-value-work-under-the-hood*/}
505505

506-
You can think of it as happening in two steps:
506+
Для простоты удобно представлять, что обновление происходит в два этапа:
507507

508-
1. **First, React re-renders with the new `query` (`"ab"`) but with the old `deferredQuery` (still `"a")`.** The `deferredQuery` value, which you pass to the result list, is *deferred:* it "lags behind" the `query` value.
508+
1. **Сначала React отрендерит компонент с новым запросом `"ab"` в `query`, но пока что с отложенным `"a"` в `deferredQuery`.** Значение в `deferredQuery`, которое вы передаёте в список результатов, является *отложенным:* оно "отстаёт" от значения `query`.
509509

510-
2. **In background, React tries to re-render with *both* `query` and `deferredQuery` updated to `"ab"`.** If this re-render completes, React will show it on the screen. However, if it suspends (the results for `"ab"` have not loaded yet), React will abandon this rendering attempt, and retry this re-render again after the data has loaded. The user will keep seeing the stale deferred value until the data is ready.
510+
2. **Затем в фоне React попытается ещё раз отрендерить компонент, но уже с новым запросом `"ab"` и в `query`, и в `deferredQuery`.** Если этот рендеринг выполнится до конца, то React отобразит его результаты на экране. Но если рендеринг задержится (встанет в ожидании результатов для `"ab"`), то React эту конкретную попытку прервёт, а когда результаты загрузятся, попробует снова. Пока данные не загрузились, пользователю будет показываться старое отложенное значение.
511511

512-
The deferred "background" rendering is interruptible. For example, if you type into the input again, React will abandon it and restart with the new value. React will always use the latest provided value.
512+
Отложенный фоновый рендеринг можно прервать. Если, например, продолжить печатать запрос, React прервёт фоновый рендеринг и перезапустит его уже с новым вводом. React всегда будет ориентироваться только на самое последнее переданное ему значение.
513513

514-
Note that there is still a network request per each keystroke. What's being deferred here is displaying results (until they're ready), not the network requests themselves. Even if the user continues typing, responses for each keystroke get cached, so pressing Backspace is instant and doesn't fetch again.
514+
В этом примере важно обратить внимание, что запросы в сеть всё ещё отправляются по каждому нажатию на клавиатуре. Откладывается здесь именно обновление результатов на экране, а не отправка в сеть запроса поиска. Просто запрос по каждому нажатию кэшируется -- поэтому по удалению символа результат уже без запроса мгновенно берётся из кэша.
515515

516516
</DeepDive>
517517

0 commit comments

Comments
 (0)