diff --git a/src/content/reference/react/Suspense.md b/src/content/reference/react/Suspense.md index 4fce69d694..41365ce29c 100644 --- a/src/content/reference/react/Suspense.md +++ b/src/content/reference/react/Suspense.md @@ -1,10 +1,9 @@ --- title: --- - -`` lets you display a fallback until its children have finished loading. +`` позволяет отображать резервный контент (fallback) до тех пор, пока его дочерние элементы не будут загружены. ```js @@ -19,28 +18,28 @@ title: --- -## Reference {/*reference*/} +## Справочник {/*reference*/} ### `` {/*suspense*/} -#### Props {/*props*/} -* `children`: The actual UI you intend to render. If `children` suspends while rendering, the Suspense boundary will switch to rendering `fallback`. -* `fallback`: An alternate UI to render in place of the actual UI if it has not finished loading. Any valid React node is accepted, though in practice, a fallback is a lightweight placeholder view, such as a loading spinner or skeleton. Suspense will automatically switch to `fallback` when `children` suspends, and back to `children` when the data is ready. If `fallback` suspends while rendering, it will activate the closest parent Suspense boundary. +#### Пропсы {/*props*/} +* `children`: Фактический UI, который вы хотите отобразить. Если `children` приостанавливает рендеринг, граница Suspense переключится на отображение `fallback`. +* `fallback`: Альтернативный UI для отображения вместо фактического UI, если он еще не загружен. Принимает любой допустимый React-узел, хотя на практике fallback представляет собой легкий заполнитель, такой как индикатор загрузки или скелет. Suspense автоматически переключится на `fallback`, когда `children` приостановится, и обратно на `children`, когда данные будут готовы. Если `fallback` приостановится во время рендеринга, он активирует ближайшую родительскую границу Suspense. -#### Caveats {/*caveats*/} +#### Особенности {/*caveats*/} -- React does not preserve any state for renders that got suspended before they were able to mount for the first time. When the component has loaded, React will retry rendering the suspended tree from scratch. -- If Suspense was displaying content for the tree, but then it suspended again, the `fallback` will be shown again unless the update causing it was caused by [`startTransition`](/reference/react/startTransition) or [`useDeferredValue`](/reference/react/useDeferredValue). -- If React needs to hide the already visible content because it suspended again, it will clean up [layout Effects](/reference/react/useLayoutEffect) in the content tree. When the content is ready to be shown again, React will fire the layout Effects again. This ensures that Effects measuring the DOM layout don't try to do this while the content is hidden. -- React includes under-the-hood optimizations like *Streaming Server Rendering* and *Selective Hydration* that are integrated with Suspense. Read [an architectural overview](https://github.com/reactwg/react-18/discussions/37) and watch [a technical talk](https://www.youtube.com/watch?v=pj5N-Khihgc) to learn more. +- React не сохраняет состояние для рендеров, которые были приостановлены до их первого монтирования. Когда компонент будет загружен, React повторит попытку рендеринга приостановленного дерева с нуля. +- Если Suspense отображал контент для дерева, но затем снова приостановился, будет показан `fallback`, если только обновление, вызвавшее это, не было вызвано [`startTransition`](/reference/react/startTransition) или [`useDeferredValue`](/reference/react/useDeferredValue). +- Если React необходимо скрыть уже видимый контент, потому что он снова приостановился, он очистит [эффекты макета](/reference/react/useLayoutEffect) в дереве контента. Когда контент будет готов к повторному отображению, React снова вызовет эффекты макета. Это гарантирует, что эффекты, измеряющие макет DOM, не будут пытаться сделать это, пока контент скрыт. +- React включает оптимизации "под капотом", такие как *потоковая серверная отрисовка* (Streaming Server Rendering) и *выборочная гидратация* (Selective Hydration), которые интегрированы с Suspense. Прочтите [обзор архитектуры](https://github.com/reactwg/react-18/discussions/37) и посмотрите [технический доклад](https://www.youtube.com/watch?v=pj5N-Khihgc), чтобы узнать больше. --- -## Usage {/*usage*/} +## Использование {/*usage*/} -### Displaying a fallback while content is loading {/*displaying-a-fallback-while-content-is-loading*/} +### Отображение запасного варианта во время загрузки контента {/*displaying-a-fallback-while-content-is-loading*/} -You can wrap any part of your application with a Suspense boundary: +Вы можете обернуть любую часть вашего приложения в границу `Suspense`: ```js [[1, 1, ""], [2, 2, ""]] }> @@ -48,9 +47,9 @@ You can wrap any part of your application with a Suspense boundary: ``` -React will display your loading fallback until all the code and data needed by the children has been loaded. +React будет отображать ваш запасной вариант загрузки до тех пор, пока не будут загружены весь код и данные, необходимые дочерним компонентам. -In the example below, the `Albums` component *suspends* while fetching the list of albums. Until it's ready to render, React switches the closest Suspense boundary above to show the fallback--your `Loading` component. Then, when the data loads, React hides the `Loading` fallback and renders the `Albums` component with data. +В приведенном ниже примере компонент `Albums` *приостанавливается* во время получения списка альбомов. Пока он не готов к отрисовке, React переключает ближайшую границу `Suspense` над ним, чтобы показать запасной вариант — ваш компонент `Loading`. Затем, когда данные загрузятся, React скроет запасной вариант `Loading` и отрисует компонент `Albums` с данными. @@ -95,7 +94,7 @@ export default function ArtistPage({ artist }) { } function Loading() { - return

🌀 Loading...

; + return

🌀 Загрузка...

; } ``` @@ -205,25 +204,25 @@ async function getAlbums() { -**Only Suspense-enabled data sources will activate the Suspense component.** They include: +**Только источники данных, поддерживающие Suspense, активируют компонент Suspense.** К ним относятся: -- Data fetching with Suspense-enabled frameworks like [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) and [Next.js](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) -- Lazy-loading component code with [`lazy`](/reference/react/lazy) -- Reading the value of a cached Promise with [`use`](/reference/react/use) +- Получение данных с помощью фреймворков, поддерживающих Suspense, таких как [Relay](https://relay.dev/docs/guided-tour/rendering/loading-states/) и [Next.js](https://nextjs.org/docs/app/building-your-application/routing/loading-ui-and-streaming#streaming-with-suspense) +- Ленивая загрузка кода компонента с помощью [`lazy`](/reference/react/lazy) +- Чтение значения кэшированного Promise с помощью [`use`](/reference/react/use) -Suspense **does not** detect when data is fetched inside an Effect or event handler. +Suspense **не** обнаруживает получение данных внутри `Effect` или обработчика событий. -The exact way you would load data in the `Albums` component above depends on your framework. If you use a Suspense-enabled framework, you'll find the details in its data fetching documentation. +Точный способ загрузки данных в компоненте `Albums` выше зависит от вашего фреймворка. Если вы используете фреймворк, поддерживающий Suspense, вы найдете подробности в его документации по получению данных. -Suspense-enabled data fetching without the use of an opinionated framework is not yet supported. The requirements for implementing a Suspense-enabled data source are unstable and undocumented. An official API for integrating data sources with Suspense will be released in a future version of React. +Получение данных с поддержкой Suspense без использования специализированного фреймворка пока не поддерживается. Требования к реализации источника данных с поддержкой Suspense нестабильны и не документированы. Официальный API для интеграции источников данных с Suspense будет выпущен в будущей версии React. --- -### Revealing content together at once {/*revealing-content-together-at-once*/} +### Одновременное отображение контента {/*revealing-content-together-at-once*/} -By default, the whole tree inside Suspense is treated as a single unit. For example, even if *only one* of these components suspends waiting for some data, *all* of them together will be replaced by the loading indicator: +По умолчанию все дерево внутри `Suspense` рассматривается как единое целое. Например, даже если *только один* из этих компонентов приостанавливается в ожидании данных, *все* они вместе будут заменены индикатором загрузки: ```js {2-5} }> @@ -234,9 +233,9 @@ By default, the whole tree inside Suspense is treated as a single unit. For exam ``` -Then, after all of them are ready to be displayed, they will all appear together at once. +Затем, после того как все они будут готовы к отображению, они появятся одновременно. -In the example below, both `Biography` and `Albums` fetch some data. However, because they are grouped under a single Suspense boundary, these components always "pop in" together at the same time. +В приведенном ниже примере и `Biography`, и `Albums` получают некоторые данные. Однако, поскольку они сгруппированы под одной границей `Suspense`, эти компоненты всегда «появляются» вместе в одно и то же время. @@ -286,7 +285,7 @@ export default function ArtistPage({ artist }) { } function Loading() { - return

🌀 Loading...

; + return

🌀 Загрузка...

; } ``` @@ -443,7 +442,7 @@ async function getAlbums() {
-Components that load data don't have to be direct children of the Suspense boundary. For example, you can move `Biography` and `Albums` into a new `Details` component. This doesn't change the behavior. `Biography` and `Albums` share the same closest parent Suspense boundary, so their reveal is coordinated together. +Компоненты, загружающие данные, не обязательно должны быть прямыми дочерними элементами `Suspense`. Например, вы можете переместить `Biography` и `Albums` в новый компонент `Details`. Это не изменит поведение. `Biography` и `Albums` имеют общий ближайший родительский компонент `Suspense`, поэтому их появление координируется вместе. ```js {2,8-11} }> @@ -464,9 +463,9 @@ function Details({ artistId }) { --- -### Revealing nested content as it loads {/*revealing-nested-content-as-it-loads*/} +### Последовательное отображение вложенного контента по мере загрузки {/*revealing-nested-content-as-it-loads*/} -When a component suspends, the closest parent Suspense component shows the fallback. This lets you nest multiple Suspense components to create a loading sequence. Each Suspense boundary's fallback will be filled in as the next level of content becomes available. For example, you can give the album list its own fallback: +Когда компонент приостанавливается, ближайший родительский компонент `Suspense` показывает запасной вариант. Это позволяет вкладывать несколько компонентов `Suspense` для создания последовательности загрузки. Запасной вариант каждой границы `Suspense` будет заполняться по мере готовности следующего уровня контента. Например, вы можете дать списку альбомов свой собственный запасной вариант: ```js {3,7} }> @@ -479,14 +478,14 @@ When a component suspends, the closest parent Suspense component shows the fallb ``` -With this change, displaying the `Biography` doesn't need to "wait" for the `Albums` to load. +С этим изменением отображение `Biography` не требует «ожидания» загрузки `Albums`. -The sequence will be: +Последовательность будет следующей: -1. If `Biography` hasn't loaded yet, `BigSpinner` is shown in place of the entire content area. -2. Once `Biography` finishes loading, `BigSpinner` is replaced by the content. -3. If `Albums` hasn't loaded yet, `AlbumsGlimmer` is shown in place of `Albums` and its parent `Panel`. -4. Finally, once `Albums` finishes loading, it replaces `AlbumsGlimmer`. +1. Если `Biography` еще не загружен, `BigSpinner` отображается вместо всей области контента. +2. Как только `Biography` завершит загрузку, `BigSpinner` будет заменен контентом. +3. Если `Albums` еще не загружен, `AlbumsGlimmer` отображается вместо `Albums` и его родительского `Panel`. +4. Наконец, как только `Albums` завершит загрузку, он заменит `AlbumsGlimmer`. @@ -538,7 +537,7 @@ export default function ArtistPage({ artist }) { } function BigSpinner() { - return

🌀 Loading...

; + return

🌀 Загрузка...

; } function AlbumsGlimmer() { @@ -722,15 +721,15 @@ async function getAlbums() {
-Suspense boundaries let you coordinate which parts of your UI should always "pop in" together at the same time, and which parts should progressively reveal more content in a sequence of loading states. You can add, move, or delete Suspense boundaries in any place in the tree without affecting the rest of your app's behavior. +Границы `Suspense` позволяют координировать, какие части вашего UI должны всегда «появляться» одновременно, а какие — постепенно раскрывать больше контента в последовательности состояний загрузки. Вы можете добавлять, перемещать или удалять границы `Suspense` в любом месте дерева, не влияя на поведение остальной части вашего приложения. -Don't put a Suspense boundary around every component. Suspense boundaries should not be more granular than the loading sequence that you want the user to experience. If you work with a designer, ask them where the loading states should be placed--it's likely that they've already included them in their design wireframes. +Не оборачивайте каждый компонент в границу `Suspense`. Границы `Suspense` не должны быть более гранулярными, чем последовательность загрузки, которую вы хотите, чтобы пользователь видел. Если вы работаете с дизайнером, спросите его, где должны располагаться состояния загрузки — вероятно, они уже включены в его макеты дизайна. --- -### Showing stale content while fresh content is loading {/*showing-stale-content-while-fresh-content-is-loading*/} +### Отображение устаревшего контента во время загрузки свежего {/*showing-stale-content-while-fresh-content-is-loading*/} -In this example, the `SearchResults` component suspends while fetching the search results. Type `"a"`, wait for the results, and then edit it to `"ab"`. The results for `"a"` will get replaced by the loading fallback. +В этом примере компонент `SearchResults` приостанавливается во время получения результатов поиска. Введите `"a"`, подождите результатов, а затем измените на `"ab"`. Результаты для `"a"` будут заменены на резервный вариант загрузки. @@ -877,7 +876,7 @@ input { margin: 10px; } -A common alternative UI pattern is to *defer* updating the list and to keep showing the previous results until the new results are ready. The [`useDeferredValue`](/reference/react/useDeferredValue) Hook lets you pass a deferred version of the query down: +Распространенный альтернативный UI-паттерн — *отложить* обновление списка и продолжать показывать предыдущие результаты до готовности новых. Хук [`useDeferredValue`](/reference/react/useDeferredValue) позволяет передать отложенную версию запроса ниже: ```js {3,11} export default function App() { @@ -897,9 +896,9 @@ export default function App() { } ``` -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. +`query` обновится немедленно, поэтому ввод будет отображать новое значение. Однако `deferredQuery` сохранит свое предыдущее значение до тех пор, пока данные не будут загружены, поэтому `SearchResults` будет некоторое время показывать устаревшие результаты. -To make it more obvious to the user, you can add a visual indication when the stale result list is displayed: +Чтобы сделать это более очевидным для пользователя, вы можете добавить визуальное указание при отображении устаревшего списка: ```js {2}
``` -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 dimmed stale result list until the new results have loaded: +Введите `"a"` в примере ниже, дождитесь загрузки результатов, а затем измените ввод на `"ab"`. Обратите внимание, что вместо резервного варианта Suspense вы теперь видите затемненный устаревший список результатов до тех пор, пока новые результаты не будут загружены: @@ -1063,15 +1062,15 @@ input { margin: 10px; } -Both deferred values and [Transitions](#preventing-already-revealed-content-from-hiding) let you avoid showing Suspense fallback in favor of inline indicators. Transitions mark the whole update as non-urgent so they are typically used by frameworks and router libraries for navigation. Deferred values, on the other hand, are mostly useful in application code where you want to mark a part of UI as non-urgent and let it "lag behind" the rest of the UI. +Как отложенные значения, так и [Transitions](#preventing-already-revealed-content-from-hiding) позволяют избежать отображения резервного варианта Suspense в пользу встроенных индикаторов. Transitions помечают все обновление как не срочное, поэтому они обычно используются фреймворками и библиотеками маршрутизации для навигации. Отложенные значения, с другой стороны, в основном полезны в коде приложения, где вы хотите пометить часть UI как не срочную и позволить ей «отставать» от остальной части UI. --- -### Preventing already revealed content from hiding {/*preventing-already-revealed-content-from-hiding*/} +### Предотвращение скрытия уже отображенного контента {/*preventing-already-revealed-content-from-hiding*/} -When a component suspends, the closest parent Suspense boundary switches to showing the fallback. This can lead to a jarring user experience if it was already displaying some content. Try pressing this button: +Когда компонент приостанавливается, ближайший родительский узел Suspense переключается на отображение резервного варианта. Это может привести к резкому пользовательскому опыту, если он уже отображал какой-то контент. Попробуйте нажать эту кнопку: @@ -1365,9 +1364,9 @@ main { -When you pressed the button, the `Router` component rendered `ArtistPage` instead of `IndexPage`. A component inside `ArtistPage` suspended, so the closest Suspense boundary started showing the fallback. The closest Suspense boundary was near the root, so the whole site layout got replaced by `BigSpinner`. +Когда вы нажали кнопку, компонент `Router` отобразил `ArtistPage` вместо `IndexPage`. Компонент внутри `ArtistPage` приостановился, поэтому ближайший узел Suspense начал показывать резервный вариант. Ближайшим узлом Suspense был узел у корня, поэтому весь макет сайта был заменен на `BigSpinner`. -To prevent this, you can mark the navigation state update as a *Transition* with [`startTransition`:](/reference/react/startTransition) +Чтобы предотвратить это, вы можете пометить обновление состояния навигации как *Transition* с помощью [`startTransition`:](/reference/react/startTransition) ```js {5,7} function Router() { @@ -1381,7 +1380,7 @@ function Router() { // ... ``` -This tells React that the state transition is not urgent, and it's better to keep showing the previous page instead of hiding any already revealed content. Now clicking the button "waits" for the `Biography` to load: +Это говорит React, что переход состояния не является срочным, и лучше продолжать показывать предыдущую страницу, а не скрывать уже отображенный контент. Теперь нажатие кнопки «ждет» загрузки `Biography`: @@ -1677,19 +1676,19 @@ main { -A Transition doesn't wait for *all* content to load. It only waits long enough to avoid hiding already revealed content. For example, the website `Layout` was already revealed, so it would be bad to hide it behind a loading spinner. However, the nested `Suspense` boundary around `Albums` is new, so the Transition doesn't wait for it. +Transition не ждет загрузки *всего* контента. Он ждет ровно столько, сколько нужно, чтобы не скрывать уже отображенный контент. Например, макет сайта `Layout` уже был отображен, поэтому было бы плохо скрывать его за индикатором загрузки. Однако вложенный узел `Suspense` вокруг `Albums` является новым, поэтому Transition его не ждет. -Suspense-enabled routers are expected to wrap the navigation updates into Transitions by default. +Предполагается, что маршрутизаторы с поддержкой Suspense по умолчанию оборачивают обновления навигации в Transitions. --- -### Indicating that a Transition is happening {/*indicating-that-a-transition-is-happening*/} +### Индикация перехода {/*indicating-that-a-transition-is-happening*/} -In the above example, once you click the button, there is no visual indication that a navigation is in progress. To add an indicator, you can replace [`startTransition`](/reference/react/startTransition) with [`useTransition`](/reference/react/useTransition) which gives you a boolean `isPending` value. In the example below, it's used to change the website header styling while a Transition is happening: +В примере выше, после нажатия кнопки, нет визуальной индикации того, что происходит навигация. Чтобы добавить индикатор, вы можете заменить [`startTransition`](/reference/react/startTransition) на [`useTransition`](/reference/react/useTransition), который возвращает булево значение `isPending`. В примере ниже оно используется для изменения стиля заголовка сайта во время перехода: @@ -1740,7 +1739,7 @@ function Router() { } function BigSpinner() { - return

🌀 Loading...

; + return

🌀 Загрузка...

; } ``` @@ -1765,7 +1764,7 @@ export default function Layout({ children, isPending }) { export default function IndexPage({ navigate }) { return ( ); } @@ -1990,27 +1989,27 @@ main { --- -### Resetting Suspense boundaries on navigation {/*resetting-suspense-boundaries-on-navigation*/} +### Сброс границ Suspense при навигации {/*resetting-suspense-boundaries-on-navigation*/} -During a Transition, React will avoid hiding already revealed content. However, if you navigate to a route with different parameters, you might want to tell React it is *different* content. You can express this with a `key`: +Во время перехода React будет избегать скрытия уже отображенного контента. Однако, если вы переходите на маршрут с другими параметрами, вы можете сообщить React, что это *другой* контент. Вы можете выразить это с помощью `key`: ```js ``` -Imagine you're navigating within a user's profile page, and something suspends. If that update is wrapped in a Transition, it will not trigger the fallback for already visible content. That's the expected behavior. +Представьте, что вы переходите между страницами профилей пользователей, и что-то вызывает приостановку рендеринга. Если это обновление обернуто в переход, оно не вызовет fallback для уже видимого контента. Это ожидаемое поведение. -However, now imagine you're navigating between two different user profiles. In that case, it makes sense to show the fallback. For example, one user's timeline is *different content* from another user's timeline. By specifying a `key`, you ensure that React treats different users' profiles as different components, and resets the Suspense boundaries during navigation. Suspense-integrated routers should do this automatically. +Однако, теперь представьте, что вы переходите между двумя разными профилями пользователей. В этом случае имеет смысл показать fallback. Например, временная шкала одного пользователя — это *другой контент*, отличный от временной шкалы другого пользователя. Указав `key`, вы гарантируете, что React будет рассматривать профили разных пользователей как разные компоненты и сбрасывать границы Suspense во время навигации. Маршрутизаторы с интеграцией Suspense должны делать это автоматически. --- -### Providing a fallback for server errors and client-only content {/*providing-a-fallback-for-server-errors-and-client-only-content*/} +### Предоставление fallback для серверных ошибок и контента, доступного только на клиенте {/*providing-a-fallback-for-server-errors-and-client-only-content*/} -If you use one of the [streaming server rendering APIs](/reference/react-dom/server) (or a framework that relies on them), React will also use your `` boundaries to handle errors on the server. If a component throws an error on the server, React will not abort the server render. Instead, it will find the closest `` component above it and include its fallback (such as a spinner) into the generated server HTML. The user will see a spinner at first. +Если вы используете один из [API серверного рендеринга с потоковой передачей](/reference/react-dom/server) (или фреймворк, который на них полагается), React также будет использовать ваши `` границы для обработки ошибок на сервере. Если компонент вызывает ошибку на сервере, React не прервет серверный рендеринг. Вместо этого он найдет ближайший `` компонент над ним и включит его fallback (например, спиннер) в сгенерированный HTML сервера. Пользователь сначала увидит спиннер. -On the client, React will attempt to render the same component again. If it errors on the client too, React will throw the error and display the closest [error boundary.](/reference/react/Component#static-getderivedstatefromerror) However, if it does not error on the client, React will not display the error to the user since the content was eventually displayed successfully. +На клиенте React попытается отрисовать тот же компонент снова. Если он также вызовет ошибку на клиенте, React выбросит ошибку и отобразит ближайший [error boundary](/reference/react/Component#static-getderivedstatefromerror). Однако, если на клиенте ошибки не будет, React не покажет ошибку пользователю, поскольку контент в конечном итоге был успешно отображен. -You can use this to opt out some components from rendering on the server. To do this, throw an error in the server environment and then wrap them in a `` boundary to replace their HTML with fallbacks: +Вы можете использовать это, чтобы исключить некоторые компоненты из рендеринга на сервере. Для этого вызовите ошибку в серверной среде, а затем оберните их в `` границу, чтобы заменить их HTML на fallback: ```js }> @@ -2025,29 +2024,29 @@ function Chat() { } ``` -The server HTML will include the loading indicator. It will be replaced by the `Chat` component on the client. +HTML сервера будет включать индикатор загрузки. Он будет заменен компонентом `Chat` на клиенте. --- -## Troubleshooting {/*troubleshooting*/} +## Устранение неполадок {/*troubleshooting*/} -### How do I prevent the UI from being replaced by a fallback during an update? {/*preventing-unwanted-fallbacks*/} +### Как предотвратить замену пользовательского интерфейса на запасной вариант во время обновления? {/*preventing-unwanted-fallbacks*/} -Replacing visible UI with a fallback creates a jarring user experience. This can happen when an update causes a component to suspend, and the nearest Suspense boundary is already showing content to the user. +Замена видимого пользовательского интерфейса на запасной вариант создает неприятные впечатления у пользователя. Это может произойти, когда обновление вызывает приостановку компонента, а ближайший `Suspense` уже отображает контент пользователю. -To prevent this from happening, [mark the update as non-urgent using `startTransition`](#preventing-already-revealed-content-from-hiding). During a Transition, React will wait until enough data has loaded to prevent an unwanted fallback from appearing: +Чтобы предотвратить это, [отметьте обновление как не срочное, используя `startTransition`](#preventing-already-revealed-content-from-hiding). Во время перехода (`Transition`) React будет ждать, пока не загрузится достаточно данных, чтобы предотвратить появление нежелательного запасного варианта: ```js {2-3,5} function handleNextPageClick() { - // If this update suspends, don't hide the already displayed content + // Если это обновление вызовет приостановку, не скрывайте уже отображенный контент startTransition(() => { setCurrentPage(currentPage + 1); }); } ``` -This will avoid hiding existing content. However, any newly rendered `Suspense` boundaries will still immediately display fallbacks to avoid blocking the UI and let the user see the content as it becomes available. +Это позволит избежать скрытия существующего контента. Однако любые вновь отображаемые `Suspense` границы по-прежнему будут немедленно показывать запасные варианты, чтобы не блокировать пользовательский интерфейс и позволить пользователю видеть контент по мере его доступности. -**React will only prevent unwanted fallbacks during non-urgent updates**. It will not delay a render if it's the result of an urgent update. You must opt in with an API like [`startTransition`](/reference/react/startTransition) or [`useDeferredValue`](/reference/react/useDeferredValue). +**React будет предотвращать нежелательные запасные варианты только во время не срочных обновлений**. Он не будет задерживать рендеринг, если он является результатом срочного обновления. Вы должны явно указать это с помощью API, такого как [`startTransition`](/reference/react/startTransition) или [`useDeferredValue`](/reference/react/useDeferredValue). -If your router is integrated with Suspense, it should wrap its updates into [`startTransition`](/reference/react/startTransition) automatically. +Если ваш роутер интегрирован с Suspense, он должен автоматически оборачивать свои обновления в [`startTransition`](/reference/react/startTransition). \ No newline at end of file