diff --git a/src/content/learn/referencing-values-with-refs.md b/src/content/learn/referencing-values-with-refs.md
index da5d864ab..77f337d88 100644
--- a/src/content/learn/referencing-values-with-refs.md
+++ b/src/content/learn/referencing-values-with-refs.md
@@ -1,49 +1,49 @@
---
-title: 'Referencing Values with Refs'
+title: 'Обращаемся к значением через рефы'
---
-When you want a component to "remember" some information, but you don't want that information to [trigger new renders](/learn/render-and-commit), you can use a *ref*.
+Для того, чтобы компонент «запомнил» какие-либо данные, но изменения этих данных не [вызывали новый рендер](/learn/render-and-commit), вы можете использовать *реф*.
-- How to add a ref to your component
-- How to update a ref's value
-- How refs are different from state
-- How to use refs safely
+- Как добавить реф в ваш компонент
+- Как обновить значение рефа
+- Отличие рефа от состояния
+- Как безопасно использовать рефы
-## Adding a ref to your component {/*adding-a-ref-to-your-component*/}
+## Добавляем реф в ваш компонент {/*adding-a-ref-to-your-component*/}
-You can add a ref to your component by importing the `useRef` Hook from React:
+Чтобы добавить реф в ваш компонент, импортируйте хук `useRef` из React:
```js
import { useRef } from 'react';
```
-Inside your component, call the `useRef` Hook and pass the initial value that you want to reference as the only argument. For example, here is a ref to the value `0`:
+Внутри компонента вызовите хук `useRef` и передайте аргумент, который будет являться начальным значением. Например, здесь значением реф является `0`:
```js
const ref = useRef(0);
```
-`useRef` returns an object like this:
+`useRef` возвращает следующий объект:
```js
-{
- current: 0 // The value you passed to useRef
+{
+ current: 0 // Значение, которое вы передали в useRef
}
```
-
+
-You can access the current value of that ref through the `ref.current` property. This value is intentionally mutable, meaning you can both read and write to it. It's like a secret pocket of your component that React doesn't track. (This is what makes it an "escape hatch" from React's one-way data flow--more on that below!)
+Получить доступ к значению рефа можно через свойство `ref.current`. Это значение намеренно является мутируемым, т.е. оно доступно как для чтения, так и для изменения. По сути, это как секретный карман, за которым React не следит. (Благодаря этому, реф является «лазейкой» в однонаправленном потоке данных React. Подробнее об этом ниже!)
-Here, a button will increment `ref.current` on every click:
+В примере ниже создадим кнопку, которая будет увеличивать `ref.current` на каждый клик:
@@ -68,20 +68,20 @@ export default function Counter() {
-The ref points to a number, but, like [state](/learn/state-a-components-memory), you could point to anything: a string, an object, or even a function. Unlike state, ref is a plain JavaScript object with the `current` property that you can read and modify.
+Здесь реф ссылается на число, но как и в случае с [состоянием](/learn/state-a-components-memory), вы можете ссылаться на что угодно: на строку, объект или даже на функцию. В отличии от состояния, реф—это обычный JavaScript-объект со свойством `current`, которое можно читать и изменять.
-Note that **the component doesn't re-render with every increment.** Like state, refs are retained by React between re-renders. However, setting state re-renders a component. Changing a ref does not!
+Имейте в виду, что **изменение реф не вызовет повторный рендер на каждое изменение.** Рефы будут сохраняться между повторными рендерами, как и состояние. Однако, обновление состояние вызывает новый рендер. А изменение рефа нет!
-## Example: building a stopwatch {/*example-building-a-stopwatch*/}
+## Пример: создадим секундомер {/*example-building-a-stopwatch*/}
-You can combine refs and state in a single component. For example, let's make a stopwatch that the user can start or stop by pressing a button. In order to display how much time has passed since the user pressed "Start", you will need to keep track of when the Start button was pressed and what the current time is. **This information is used for rendering, so you'll keep it in state:**
+Рефы и состояние можно использовать в одном компоненте. Например, создадим секундомер, который можно будет запускать и останавливать нажатием кнопки. Чтобы отобразить сколько времени прошло с момента клика «Start», нужно следить за моментом клика и за текущим временем. **Так как эти данные используются при рендере, их лучше хранить в состоянии:**
```js
const [startTime, setStartTime] = useState(null);
const [now, setNow] = useState(null);
```
-When the user presses "Start", you'll use [`setInterval`](https://developer.mozilla.org/docs/Web/API/setInterval) in order to update the time every 10 milliseconds:
+Чтобы обновлять время каждые 10 миллисекунд, после того как пользователь нажимает «Start», будем использовать [`setInterval`](https://developer.mozilla.org/docs/Web/API/setInterval):
@@ -93,12 +93,12 @@ export default function Stopwatch() {
const [now, setNow] = useState(null);
function handleStart() {
- // Start counting.
+ // Начинаем отсчёт.
setStartTime(Date.now());
setNow(Date.now());
setInterval(() => {
- // Update the current time every 10ms.
+ // Обновляем текущее время каждые 10мс.
setNow(Date.now());
}, 10);
}
@@ -121,7 +121,7 @@ export default function Stopwatch() {
-When the "Stop" button is pressed, you need to cancel the existing interval so that it stops updating the `now` state variable. You can do this by calling [`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval), but you need to give it the interval ID that was previously returned by the `setInterval` call when the user pressed Start. You need to keep the interval ID somewhere. **Since the interval ID is not used for rendering, you can keep it in a ref:**
+Когда нажата кнопка «Stop», нужно очистить текущий интервал, чтобы значение состояния `now` перестало обновляться. Для реализации можно использовать вызов[`clearInterval`](https://developer.mozilla.org/en-US/docs/Web/API/clearInterval), но интервалу нужно задать ID, которое возвращается при вызове `setInterval`, когда пользователь нажал «Start». ID интервала нужно где-то сохранить. **Поскольку ID интервала не используется для рендера, вы можете сохранить его в реф:**
@@ -168,20 +168,20 @@ export default function Stopwatch() {
-When a piece of information is used for rendering, keep it in state. When a piece of information is only needed by event handlers and changing it doesn't require a re-render, using a ref may be more efficient.
+Когда какие-то данные используются для рендера, держите её в состоянии. Когда данные нужны только для обработчиков событий, и изменение этих данных не требуют повторного рендера, использование реф будет более эффективным.
-## Differences between refs and state {/*differences-between-refs-and-state*/}
+## Отличие рефа от состояния {/*differences-between-refs-and-state*/}
-Perhaps you're thinking refs seem less "strict" than state—you can mutate them instead of always having to use a state setting function, for instance. But in most cases, you'll want to use state. Refs are an "escape hatch" you won't need often. Here's how state and refs compare:
+Может показаться, что рефы менее «строгие», чем состояние—их можно изменять напрямую, вместо использования функции для обновления состояния. Но в большинстве случаев вам захочется использовать состояние. Рефы—это «лазейка», которую не рекомендуется использовать слишком часто. Ниже сравнение рефа и состояния:
-| refs | state |
+| refs | state |
| ------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------- |
-| `useRef(initialValue)` returns `{ current: initialValue }` | `useState(initialValue)` returns the current value of a state variable and a state setter function ( `[value, setValue]`) |
-| Doesn't trigger re-render when you change it. | Triggers re-render when you change it. |
-| Mutable—you can modify and update `current`'s value outside of the rendering process. | "Immutable"—you must use the state setting function to modify state variables to queue a re-render. |
-| You shouldn't read (or write) the `current` value during rendering. | You can read state at any time. However, each render has its own [snapshot](/learn/state-as-a-snapshot) of state which does not change.
+| `useRef(initialValue)` возвращает `{ current: initialValue }` | `useState(initialValue)` возвращает текущее значение состояния и функцию-сеттер для его обновления ( `[value, setValue]`) |
+| При изменении не вызывает повторный рендер. | При изменении вызывает повторный рендер. |
+| Мутабельный—можно изменять и обновлять значение `current` независимо от процесса рендера. | «Иммутабельный»—обязательно использовать функцию-сеттер, чтобы добавить изменение состояния в очередь обновлений. |
+| Не рекомендуется читать (или изменять) значение `current` во время рендера. | Можно читать значение состояния в любое время. Однако, за каждым рендером закреплён свой [снимок](/learn/state-as-a-snapshot) состояния, который не будет изменяться.
-Here is a counter button that's implemented with state:
+В следующем примере создадим кнопку счётчика, которая использует состояние:
@@ -205,9 +205,9 @@ export default function Counter() {
-Because the `count` value is displayed, it makes sense to use a state value for it. When the counter's value is set with `setCount()`, React re-renders the component and the screen updates to reflect the new count.
+В этом случае имеет смысл использовать состояние, т.к. значение `count` отображается на странице. Когда состояние счётчика обновляется при помощи `setCount()`, React вызывает повторный рендер и на экране отображается новое значение счётчика.
-If you tried to implement this with a ref, React would never re-render the component, so you'd never see the count change! See how clicking this button **does not update its text**:
+Если использовать реф, React никогда не вызовет повторный рендер, поэтому вы никогда не увидите изменение счётчика! Например, в данном случае клик по кнопке **не обновляет её текст**:
@@ -218,7 +218,7 @@ export default function Counter() {
let countRef = useRef(0);
function handleClick() {
- // This doesn't re-render the component!
+ // Повторный рендер не вызовется!
countRef.current = countRef.current + 1;
}
@@ -232,68 +232,68 @@ export default function Counter() {
-This is why reading `ref.current` during render leads to unreliable code. If you need that, use state instead.
+Именно поэтому чтение из `ref.current` во время рендера приводит к непредсказуемому результату. Используйте состояние, если во время рендера вам точно нужно читать данные из него!
-#### How does useRef work inside? {/*how-does-use-ref-work-inside*/}
+#### Как работает useRef изнутри? {/*how-does-use-ref-work-inside*/}
-Although both `useState` and `useRef` are provided by React, in principle `useRef` could be implemented _on top of_ `useState`. You can imagine that inside of React, `useRef` is implemented like this:
+Хотя оба хука `useState` и `useRef` могут быть импортированы из React, `useRef` может быть реализован поверх `useState`. Можно представлять, что внутри React `useRef` реализован следующим образом:
```js
-// Inside of React
+// Внутри React
function useRef(initialValue) {
const [ref, unused] = useState({ current: initialValue });
return ref;
}
```
-During the first render, `useRef` returns `{ current: initialValue }`. This object is stored by React, so during the next render the same object will be returned. Note how the state setter is unused in this example. It is unnecessary because `useRef` always needs to return the same object!
+Во время первого рендера `useRef` возвращает `{ current: initialValue }`. Этот объект сохраняется внутри React, поэтому во время следующего рендера вернётся точно такой же объект. Обратите внимание, что функция для обновления состояния в этом примере не используется. В этом нет необходимости, т.к. `useRef` всегда возвращает один и тот же объект!
-React provides a built-in version of `useRef` because it is common enough in practice. But you can think of it as a regular state variable without a setter. If you're familiar with object-oriented programming, refs might remind you of instance fields--but instead of `this.something` you write `somethingRef.current`.
+React предоставляет встроенный хук `useRef`, т.к. это достаточно часто встречается на практике. Но можно представлять себе, что это обычное значение состояния, но без функции обновления. Если вы знакомы с объектно-ориентированным программированием, рефы могут напоминать вам поля экземпляра--но вместо `this.something` используется `somethingRef.current`.
-## When to use refs {/*when-to-use-refs*/}
+## Когда использовать рефы {/*when-to-use-refs*/}
-Typically, you will use a ref when your component needs to "step outside" React and communicate with external APIs—often a browser API that won't impact the appearance of the component. Here are a few of these rare situations:
+Как правило, вы будете использовать реф, когда захотите выйти за пределы парадигмы React и иметь возможность взаимодействовать со сторонними API—часто это API браузера, которое никак не влияет на отображение компонента на странице. Ниже приведены примеры таких ситуаций:
-- Storing [timeout IDs](https://developer.mozilla.org/docs/Web/API/setTimeout)
-- Storing and manipulating [DOM elements](https://developer.mozilla.org/docs/Web/API/Element), which we cover on [the next page](/learn/manipulating-the-dom-with-refs)
-- Storing other objects that aren't necessary to calculate the JSX.
+- Хранение [ID таймера](https://developer.mozilla.org/docs/Web/API/setTimeout)
+- Хранение и манипулирование [DOM-элементами](https://developer.mozilla.org/docs/Web/API/Element), которое мы разберём [в следующей главе](/learn/manipulating-the-dom-with-refs)
+- Хранение различных других объектов, которые не влияют на JSX.
-If your component needs to store some value, but it doesn't impact the rendering logic, choose refs.
+Если вы хотите сохранить какое-то значение внутри компонента, которое не влияет на логику рендера, используйте реф.
-## Best practices for refs {/*best-practices-for-refs*/}
+## Рекомендации по использованию рефов {/*best-practices-for-refs*/}
-Following these principles will make your components more predictable:
+Следуйте следующим принципам, чтобы сделать ваши компоненты более предсказуемыми:
-- **Treat refs as an escape hatch.** Refs are useful when you work with external systems or browser APIs. If much of your application logic and data flow relies on refs, you might want to rethink your approach.
-- **Don't read or write `ref.current` during rendering.** If some information is needed during rendering, use [state](/learn/state-a-components-memory) instead. Since React doesn't know when `ref.current` changes, even reading it while rendering makes your component's behavior difficult to predict. (The only exception to this is code like `if (!ref.current) ref.current = new Thing()` which only sets the ref once during the first render.)
+- **Используйте рефы как лазейку.** Использование рефов является оправданным, когда вы работаете со сторонними системами или с API браузера. Если большая часть логики вашего приложения и потока данных зависит от рефов, скорее всего вам стоит переосмыслить свой подход.
+- **Не читайте и не изменяйте `ref.current` во время рендера.** Если необходимо использовать какие-то данные во время рендера, используйте [состояние](/learn/state-a-components-memory) вместо рефа. Даже просто чтение во время рендера делает поведение вашего компонента менее предсказуемым, поскольку React ничего не знает об изменении `ref.current`. (Единственным исключением является `if (!ref.current) ref.current = new Thing()`, где реф устанавливается единожды, во время первого рендера.)
-Limitations of React state don't apply to refs. For example, state acts like a [snapshot for every render](/learn/state-as-a-snapshot) and [doesn't update synchronously.](/learn/queueing-a-series-of-state-updates) But when you mutate the current value of a ref, it changes immediately:
+Ограничения React при использовании состояния никак не влияют на рефы. Например, состояние ведёт себя как [снимок для каждого рендера](/learn/state-as-a-snapshot) и [не обновляется синхронно.](/learn/queueing-a-series-of-state-updates) Но при изменении текущего значения реф, оно изменяется сразу же:
```js
ref.current = 5;
console.log(ref.current); // 5
```
-This is because **the ref itself is a regular JavaScript object,** and so it behaves like one.
+Это обусловлено тем, что **реф—это обычный JavaScript-объект,** и ведёт себя как объект.
-You also don't need to worry about [avoiding mutation](/learn/updating-objects-in-state) when you work with a ref. As long as the object you're mutating isn't used for rendering, React doesn't care what you do with the ref or its contents.
+Когда вы работаете с рефами, вам не нужно беспокоится о том, чтобы [избегать мутаций](/learn/updating-objects-in-state). До тех пор пока объект, который вы мутируете не используется для рендера, React нет дела, что вы делаете с рефами и их значениями.
-## Refs and the DOM {/*refs-and-the-dom*/}
+## Рефы и DOM {/*refs-and-the-dom*/}
-You can point a ref to any value. However, the most common use case for a ref is to access a DOM element. For example, this is handy if you want to focus an input programmatically. When you pass a ref to a `ref` attribute in JSX, like `
`, React will put the corresponding DOM element into `myRef.current`. You can read more about this in [Manipulating the DOM with Refs.](/learn/manipulating-the-dom-with-refs)
+Вы можете использовать реф в качестве ссылки на любое значение. Однако, на практике рефы часто используются для доступа к DOM-элементам. Например, когда нужно программно сфокусироваться на элементе `input`. Когда вы устанавливаете `ref` через атрибут, `
`, React сохранит соответствующий DOM-элемент в качестве значения `myRef.current`. Вы можете больше прочитать об этом в [Manipulating the DOM with Refs.](/learn/manipulating-the-dom-with-refs).
-- Refs are an escape hatch to hold onto values that aren't used for rendering. You won't need them often.
-- A ref is a plain JavaScript object with a single property called `current`, which you can read or set.
-- You can ask React to give you a ref by calling the `useRef` Hook.
-- Like state, refs let you retain information between re-renders of a component.
-- Unlike state, setting the ref's `current` value does not trigger a re-render.
-- Don't read or write `ref.current` during rendering. This makes your component hard to predict.
+- Рефф—это лазейка для хранения значений, которые не используются при рендере. Чаще всего вы можете обойтись без них.
+- Реф—это обычный JavaScript-объект с единственным свойством `curent`, которое доступно как для чтения, так и для записи.
+- Вы можете использовать реф, вызвав хук `useRef` из React.
+- Рефы позволяют вам сохранить данные между перерисовками компонента, как и в случае с состоянием.
+- В отличии от состояния, запись нового значения в `ref.current` не спровоцирует повторный рендер компонента.
+- Не читайте и не записывайте ничего в `ref.current` во время рендера. Это сделает поведение вашего компонента менее предсказуемым.
@@ -301,13 +301,13 @@ You can point a ref to any value. However, the most common use case for a ref is
-#### Fix a broken chat input {/*fix-a-broken-chat-input*/}
+#### Исправьте неработающий input в чате {/*fix-a-broken-chat-input*/}
-Type a message and click "Send". You will notice there is a three second delay before you see the "Sent!" alert. During this delay, you can see an "Undo" button. Click it. This "Undo" button is supposed to stop the "Sent!" message from appearing. It does this by calling [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) for the timeout ID saved during `handleSend`. However, even after "Undo" is clicked, the "Sent!" message still appears. Find why it doesn't work, and fix it.
+Введите сообщение и нажмите «Send». Можно заметить трёхсекундную задержку перед тем, как появится модальное окно с сообщением «Sent!». Во время этой задержки появляется кнопка «Undo». Кликните по ней. Предполагается, что кнопка «Undo» предотвратит появление сообщения «Sent!». Это происходит из-за вызова [`clearTimeout`](https://developer.mozilla.org/en-US/docs/Web/API/clearTimeout) для сохранения ID во время `handleSend`. Однако, даже после клика «Undo», сообщение все ещё появляется. Попробуйте разобраться, почему этот код не работает, и исправить его.
-Regular variables like `let timeoutID` don't "survive" between re-renders because every render runs your component (and initializes its variables) from scratch. Should you keep the timeout ID somewhere else?
+Обычные переменные, такие как `let timeoutID` не «выживают» между повторными рендерами, потому что каждый рендер запускает компонент (и инициализирует переменные) с нуля.
@@ -360,7 +360,7 @@ export default function Chat() {
-Whenever your component re-renders (such as when you set state), all local variables get initialized from scratch. This is why you can't save the timeout ID in a local variable like `timeoutID` and then expect another event handler to "see" it in the future. Instead, store it in a ref, which React will preserve between renders.
+Каждый раз когда компонент рендерится повторно (например, когда устанавливается новое состояние), все локальные переменные инициализируются с нуля. Поэтому вы не можете сохранить ID таймера в обычную переменную, как `timeoutID` и ожидать, что обработчик сможет «увидеть» её в будущем. Вместо этого сохраните её в реф, который React сохраняет между рендерами.
@@ -412,9 +412,9 @@ export default function Chat() {
-#### Fix a component failing to re-render {/*fix-a-component-failing-to-re-render*/}
+#### Исправьте ошибку при повторном рендере компонента {/*fix-a-component-failing-to-re-render*/}
-This button is supposed to toggle between showing "On" and "Off". However, it always shows "Off". What is wrong with this code? Fix it.
+Предполагается, что кнопка должна переключаться между отображением «On» и «Off». Но всегда отображается «Off». Что не так с эти кодом? Попробуйте исправить.
@@ -438,7 +438,7 @@ export default function Toggle() {
-In this example, the current value of a ref is used to calculate the rendering output: `{isOnRef.current ? 'On' : 'Off'}`. This is a sign that this information should not be in a ref, and should have instead been put in state. To fix it, remove the ref and use state instead:
+В этом примере текущее значение реф используется для вычисления того, что отобразится на странице: `{isOnRef.current ? 'On' : 'Off'}`. Это признак того, что эти данные не должны хранится в рефе, и вместо этого должны храниться в состоянии. Чтобы исправить, удалите реф и используйте состояние вместо него:
@@ -462,17 +462,17 @@ export default function Toggle() {
-#### Fix debouncing {/*fix-debouncing*/}
+#### Исправьте debouncing {/*fix-debouncing*/}
-In this example, all button click handlers are ["debounced".](https://redd.one/blog/debounce-vs-throttle) To see what this means, press one of the buttons. Notice how the message appears a second later. If you press the button while waiting for the message, the timer will reset. So if you keep clicking the same button fast many times, the message won't appear until a second *after* you stop clicking. Debouncing lets you delay some action until the user "stops doing things".
+В данном примере все обработчики событий для кнопок являются ["debounced".](https://redd.one/blog/debounce-vs-throttle) Чтобы понять, как это работает, кликните на одну из кнопок. Обратите внимание, что сообщение появляется через секунду. Если нажать на кнопку во время ожидания сообщения, таймер сбросится. Таким образом, если вы продолжите кликать одну и ту же кнопку много раз, сообщение не появится до тех пор, пока не пройдёт секунда _после_ последнего клика. Debouncing позволяет вам установить задержку до тех пор, пока пользователь «не прекратит делать что-то», прежде чем произойдёт какое-то действие.
-This example works, but not quite as intended. The buttons are not independent. To see the problem, click one of the buttons, and then immediately click another button. You'd expect that after a delay, you would see both button's messages. But only the last button's message shows up. The first button's message gets lost.
+Этот пример работает, но не совсем как было задумано. Кнопки не являются независимыми. Чтобы увидеть проблему, кликните на одну из кнопок и затем кликните на другую кнопку. Мы ожидаем увидеть два сообщения, которые привязаны к каждой кнопке. Но мы увидим только сообщение последней. Сообщение первой кнопки потерялось.
-Why are the buttons interfering with each other? Find and fix the issue.
+Почему кнопки конфликтуют между собой? Попробуйте найти и исправить проблему.
-The last timeout ID variable is shared between all `DebouncedButton` components. This is why clicking one button resets another button's timeout. Can you store a separate timeout ID for each button?
+Последний ID таймера используется во всех компонентах `DebouncedButton`. В этом причина того, что клик по одной кнопке сбрасывает таймер другой. Можно ли хранить ID таймера отдельно для каждой из кнопок?
@@ -525,7 +525,7 @@ button { display: block; margin: 10px; }
-A variable like `timeoutID` is shared between all components. This is why clicking on the second button resets the first button's pending timeout. To fix this, you can keep timeout in a ref. Each button will get its own ref, so they won't conflict with each other. Notice how clicking two buttons fast will show both messages.
+Переменная `timeoutID` была использована во всех компонентах. Поэтому клик по второй кнопке сбрасывал таймер ожидания первой. Чтобы это исправить, следует хранить таймер в рефе. Каждая кнопка получит свой реф, и вместе кнопки будут работать корректно. Обратите внимание, что быстрый клик по двум кнопкам покажет оба сообщения.
@@ -577,11 +577,11 @@ button { display: block; margin: 10px; }
-#### Read the latest state {/*read-the-latest-state*/}
+#### Прочитайте самое новое состояние {/*read-the-latest-state*/}
-In this example, after you press "Send", there is a small delay before the message is shown. Type "hello", press Send, and then quickly edit the input again. Despite your edits, the alert would still show "hello" (which was the value of state [at the time](/learn/state-as-a-snapshot#state-over-time) the button was clicked).
+В данном примере, после нажатия «Send» есть небольшая задержка прежде чем появится сообщение. Введите «hello», нажмите Send и потом снова отредактируйте поле ввода. Несмотря на редактирование, модальное окно все ещё показывает «hello» (эта строка была значением состояния [во время](/learn/state-as-a-snapshot#state-over-time), когда произошёл клик по кнопке).
-Usually, this behavior is what you want in an app. However, there may be occasional cases where you want some asynchronous code to read the *latest* version of some state. Can you think of a way to make the alert show the *current* input text rather than what it was at the time of the click?
+Как правило, именно такое поведение вам необходимо в вашем приложении. Тем не менее, могут возникнуть случаи, когда будет необходимость получить доступ к самой _последней_ версии состояния в каком-либо асинхронном коде. Можете ли вы найти решение, чтобы модальное окно показывало _текущий_ текст поля ввода вместо состояния, которое сохранилось во время клика?
@@ -616,7 +616,7 @@ export default function Chat() {
-State works [like a snapshot](/learn/state-as-a-snapshot), so you can't read the latest state from an asynchronous operation like a timeout. However, you can keep the latest input text in a ref. A ref is mutable, so you can read the `current` property at any time. Since the current text is also used for rendering, in this example, you will need *both* a state variable (for rendering), *and* a ref (to read it in the timeout). You will need to update the current ref value manually.
+Состояние работает как [снимок](/learn/state-as-a-snapshot), поэтому вы не сможете получить доступ к его последней версии из асинхронного кода, например внутри таймера. Однако, вы можете хранить последнее значение поля ввода в рефе. Реф является мутируемым, поэтому свойство `current` доступно для чтения в любое время. Поскольку, в этом примере, введённый текст также используется для рендера, вам необходимо использовать и *состояние* переменной (для рендера), и *реф* (для чтения внутри таймера). Обновляйте текущий реф вручную.
@@ -657,4 +657,4 @@ export default function Chat() {
-
+
\ No newline at end of file