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
Copy file name to clipboardExpand all lines: src/content/reference/react/useDeferredValue.md
+20-20Lines changed: 20 additions & 20 deletions
Original file line number
Diff line number
Diff line change
@@ -730,11 +730,11 @@ input { margin: 10px; }
730
730
731
731
---
732
732
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*/}
734
734
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.
736
736
737
-
Imagine you have a text field and a component (like a chart or a long list) that re-renders on every keystroke:
737
+
Представьте, что в вашем приложении некий сложный компонент (график, либо очень длинный список) каждый раз заново рендерится по каждому нажатию клавиши в поле ввода:
738
738
739
739
```js
740
740
functionApp() {
@@ -748,17 +748,17 @@ function App() {
748
748
}
749
749
```
750
750
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` не повторялся, если его пропсы не меняются.
752
752
753
753
```js {1,3}
754
754
constSlowList=memo(functionSlowList({ text }) {
755
755
// ...
756
756
});
757
757
```
758
758
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`*одни и те же* значения пропсов. Проблема в том, что рендеринг всё ещё медленный, если передавать *другие* значения пропсов, требующие другой визуализации.
760
760
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`можно сделать обновления поля ввода всегда более приоритетными (отзывчивее), чем обновления списка (которые в любом случае медленные):
762
762
763
763
```js {3,7}
764
764
functionApp() {
@@ -773,13 +773,13 @@ function App() {
773
773
}
774
774
```
775
775
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 будет стараться обновлять список как можно раньше, но уже не в ущерб возможности печатать.
777
777
778
-
<RecipestitleText="The difference between useDeferredValue and unoptimized re-rendering"titleId="examples">
778
+
<RecipestitleText="Сравнение: useDeferredValue против неоптимизированного рендеринга"titleId="examples">
779
779
780
-
#### Deferred re-rendering of the list {/*deferred-re-rendering-of-the-list*/}
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`позволяет сохранить отзывчивость поля ввода. Попробуйте попечатать в поле ввода -- оцените свои ощущения от того, как мгновенно оно реагирует на ввод, хотя список при этом заметно отстаёт.
783
783
784
784
<Sandpack>
785
785
@@ -803,7 +803,7 @@ export default function App() {
803
803
import { memo } from'react';
804
804
805
805
constSlowList=memo(functionSlowList({ text }) {
806
-
//Log once. The actual slowdown is inside SlowItem.
In this example, each item in the`SlowList`component is **artificially slowed down**, but there is no `useDeferredValue`.
858
+
В этом примере каждый элемент в компоненте`SlowList`**искусственно замедлен**, но `useDeferredValue` уже не используется.
859
859
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` каждое нажатие клавиши требует немедленно заново отрендерить список. Причём без возможности прерывать рендеринг.
861
861
862
862
<Sandpack>
863
863
@@ -880,7 +880,7 @@ export default function App() {
880
880
import { memo } from'react';
881
881
882
882
constSlowList=memo(functionSlowList({ text }) {
883
-
//Log once. The actual slowdown is inside SlowItem.
//Do nothing for 1 ms per item to emulate extremely slow code
900
+
//Крутимся в цикле одну миллисекунду, эмулируя очень медленный рендеринг
901
901
}
902
902
903
903
return (
904
904
<li className="item">
905
-
Text: {text}
905
+
Текст: {text}
906
906
</li>
907
907
)
908
908
}
@@ -934,7 +934,7 @@ export default SlowList;
934
934
935
935
<Pitfall>
936
936
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)список всё равно будет рендерится ещё раз -- что делает саму оптимизацию бессмысленной.
0 commit comments