Skip to content

Commit f8806c7

Browse files
committed
Translated more usage of useDeferredValue
1 parent 1e7fc43 commit f8806c7

File tree

1 file changed

+20
-20
lines changed

1 file changed

+20
-20
lines changed

src/content/reference/react/useDeferredValue.md

Lines changed: 20 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -730,11 +730,11 @@ input { margin: 10px; }
730730

731731
---
732732

733-
### Deferring re-rendering for a part of the UI {/*deferring-re-rendering-for-a-part-of-the-ui*/}
733+
### Откладывание повторного рендеринга для части UI {/*deferring-re-rendering-for-a-part-of-the-ui*/}
734734

735-
You can also apply `useDeferredValue` as a performance optimization. It is useful when a part of your UI is slow to re-render, there's no easy way to optimize it, and you want to prevent it from blocking the rest of the UI.
735+
`useDeferredValue` -- это в том числе инструмент оптимизации. Его можно применить в ситуации, когда какая-то часть вашего UI требует вычислительно долгого рендеринга, с которым очень трудно что-то сделать, но при этом вы не хотите из-за этого постоянно блокировать рендеринг остального UI.
736736

737-
Imagine you have a text field and a component (like a chart or a long list) that re-renders on every keystroke:
737+
Представьте, что в вашем приложении некий сложный компонент (график, либо очень длинный список) каждый раз заново рендерится по каждому нажатию клавиши в поле ввода:
738738

739739
```js
740740
function App() {
@@ -748,17 +748,17 @@ function App() {
748748
}
749749
```
750750

751-
First, optimize `SlowList` to skip re-rendering when its props are the same. To do this, [wrap it in `memo`:](/reference/react/memo#skipping-re-rendering-when-props-are-unchanged)
751+
Для начала, вы можете [обернуть `SlowList` в `memo`](/reference/react/memo#skipping-re-rendering-when-props-are-unchanged), чтобы рендеринг `SlowList` не повторялся, если его пропсы не меняются.
752752

753753
```js {1,3}
754754
const SlowList = memo(function SlowList({ text }) {
755755
// ...
756756
});
757757
```
758758

759-
However, this only helps if the `SlowList` props are *the same* as during the previous render. The problem you're facing now is that it's slow when they're *different,* and when you actually need to show different visual output.
759+
Но этого не достаточно. Ведь так рендеринг ускорится, только если всегда передавать в `SlowList` *одни и те же* значения пропсов. Проблема в том, что рендеринг всё ещё медленный, если передавать *другие* значения пропсов, требующие другой визуализации.
760760

761-
Concretely, the main performance problem is that whenever you type into the input, the `SlowList` receives new props, and re-rendering its entire tree makes the typing feel janky. In this case, `useDeferredValue` lets you prioritize updating the input (which must be fast) over updating the result list (which is allowed to be slower):
761+
Конкретно в этом примере, `SlowList` будет на каждый ввод символа получать новые пропсы и своим рендерингом блокировать остальной интерфейс. Из-за чего ввод будет слишком заметно "заедать". В такой ситуации с помощью `useDeferredValue` можно сделать обновления поля ввода всегда более приоритетными (отзывчивее), чем обновления списка (которые в любом случае медленные):
762762

763763
```js {3,7}
764764
function App() {
@@ -773,13 +773,13 @@ function App() {
773773
}
774774
```
775775

776-
This does not make re-rendering of the `SlowList` faster. However, it tells React that re-rendering the list can be deprioritized so that it doesn't block the keystrokes. The list will "lag behind" the input and then "catch up". Like before, React will attempt to update the list as soon as possible, but will not block the user from typing.
776+
Собственно сам рендеринг `SlowList` не станет от этого быстрее. Однако теперь React понимает, что не нужно блокировать обработку нажатий рендерингом списка. Визуально список будет как бы "отставать" от ввода, а затем его "догонять". Конечно, как и до оптимизации, React будет стараться обновлять список как можно раньше, но уже не в ущерб возможности печатать.
777777

778-
<Recipes titleText="The difference between useDeferredValue and unoptimized re-rendering" titleId="examples">
778+
<Recipes titleText="Сравнение: useDeferredValue против неоптимизированного рендеринга" titleId="examples">
779779

780-
#### Deferred re-rendering of the list {/*deferred-re-rendering-of-the-list*/}
780+
#### Отложенный рендеринг списка {/*deferred-re-rendering-of-the-list*/}
781781

782-
In this example, each item in the `SlowList` component is **artificially slowed down** so that you can see how `useDeferredValue` lets you keep the input responsive. Type into the input and notice that typing feels snappy while the list "lags behind" it.
782+
В этом примере каждый элемент в компоненте `SlowList` **искусственно замедлен**, чтобы продемонстрировать, как `useDeferredValue` позволяет сохранить отзывчивость поля ввода. Попробуйте попечатать в поле ввода -- оцените свои ощущения от того, как мгновенно оно реагирует на ввод, хотя список при этом заметно отстаёт.
783783

784784
<Sandpack>
785785

@@ -803,7 +803,7 @@ export default function App() {
803803
import { memo } from 'react';
804804

805805
const SlowList = memo(function SlowList({ text }) {
806-
// Log once. The actual slowdown is inside SlowItem.
806+
// Собственно замедление происходит в SlowItem.
807807
console.log('[ARTIFICIALLY SLOW] Rendering 250 <SlowItem />');
808808

809809
let items = [];
@@ -820,12 +820,12 @@ const SlowList = memo(function SlowList({ text }) {
820820
function SlowItem({ text }) {
821821
let startTime = performance.now();
822822
while (performance.now() - startTime < 1) {
823-
// Do nothing for 1 ms per item to emulate extremely slow code
823+
// Крутимся в цикле одну миллисекунду, эмулируя очень медленный рендеринг
824824
}
825825

826826
return (
827827
<li className="item">
828-
Text: {text}
828+
Текст: {text}
829829
</li>
830830
)
831831
}
@@ -853,11 +853,11 @@ export default SlowList;
853853

854854
<Solution />
855855

856-
#### Unoptimized re-rendering of the list {/*unoptimized-re-rendering-of-the-list*/}
856+
#### Неоптимизированный рендеринг списка {/*unoptimized-re-rendering-of-the-list*/}
857857

858-
In this example, each item in the `SlowList` component is **artificially slowed down**, but there is no `useDeferredValue`.
858+
В этом примере каждый элемент в компоненте `SlowList` **искусственно замедлен**, но `useDeferredValue` уже не используется.
859859

860-
Notice how typing into the input feels very janky. This is because without `useDeferredValue`, each keystroke forces the entire list to re-render immediately in a non-interruptible way.
860+
Обратите внимание, как поле ввода заедает при каждом нажатии. Так происходит потому, что без `useDeferredValue` каждое нажатие клавиши требует немедленно заново отрендерить список. Причём без возможности прерывать рендеринг.
861861

862862
<Sandpack>
863863

@@ -880,7 +880,7 @@ export default function App() {
880880
import { memo } from 'react';
881881

882882
const SlowList = memo(function SlowList({ text }) {
883-
// Log once. The actual slowdown is inside SlowItem.
883+
// Собственно замедление происходит в SlowItem.
884884
console.log('[ARTIFICIALLY SLOW] Rendering 250 <SlowItem />');
885885

886886
let items = [];
@@ -897,12 +897,12 @@ const SlowList = memo(function SlowList({ text }) {
897897
function SlowItem({ text }) {
898898
let startTime = performance.now();
899899
while (performance.now() - startTime < 1) {
900-
// Do nothing for 1 ms per item to emulate extremely slow code
900+
// Крутимся в цикле одну миллисекунду, эмулируя очень медленный рендеринг
901901
}
902902

903903
return (
904904
<li className="item">
905-
Text: {text}
905+
Текст: {text}
906906
</li>
907907
)
908908
}
@@ -934,7 +934,7 @@ export default SlowList;
934934

935935
<Pitfall>
936936

937-
This optimization requires `SlowList` to be wrapped in [`memo`.](/reference/react/memo) This is because whenever the `text` changes, React needs to be able to re-render the parent component quickly. During that re-render, `deferredText` still has its previous value, so `SlowList` is able to skip re-rendering (its props have not changed). Without [`memo`,](/reference/react/memo) it would have to re-render anyway, defeating the point of the optimization.
937+
Для такой оптимизации `SlowList` должен обязательно быть обёрнут в [`memo`.](/reference/react/memo) Цель оптимизации ведь в том, чтобы при каждом изменении `text` React рендерил родительский компонент (`App`) как можно быстрей. Во время этого рендеринга в `deferredText` будет такое же значение, как и в прошлый рендеринг -- а значит пропсы `SlowList` не изменились, и нет нужды заново рендерить список. Но без [`memo`](/reference/react/memo) список всё равно будет рендерится ещё раз -- что делает саму оптимизацию бессмысленной.
938938

939939
</Pitfall>
940940

0 commit comments

Comments
 (0)