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/hooks.md
+37-37Lines changed: 37 additions & 37 deletions
Display the source diff
Display the rich diff
Original file line number
Diff line number
Diff line change
@@ -4,20 +4,20 @@ title: "Built-in React Hooks"
4
4
5
5
<Intro>
6
6
7
-
*Hooks* let you use different React features from your components. You can either use the built-in Hooks or combine them to build your own. This page lists all built-in Hooks in React.
7
+
*Хуки* позволяют использовать различные возможности React в ваших компонентах. Вы можете использовать встроенные хуки или комбинировать их для создания собственных. На этой странице перечислены все встроенные хуки React.
8
8
9
9
</Intro>
10
10
11
11
---
12
12
13
-
## State Hooks {/*state-hooks*/}
13
+
## Хуки состояния {/*state-hooks*/}
14
14
15
-
*State* lets a component ["remember" information like user input.](/learn/state-a-components-memory)For example, a form component can use state to store the input value, while an image gallery component can use state to store the selected image index.
15
+
*Состояние* позволяет компоненту ["запоминать" информацию, такую как ввод пользователя.](/learn/state-a-components-memory)Например, компонент формы может использовать состояние для хранения введенного значения, а компонент галереи изображений — для хранения индекса выбранного изображения.
16
16
17
-
To add state to a component, use one of these Hooks:
17
+
Чтобы добавить состояние в компонент, используйте один из этих хуков:
18
18
19
-
*[`useState`](/reference/react/useState)declares a state variable that you can update directly.
20
-
*[`useReducer`](/reference/react/useReducer)declares a state variable with the update logic inside a [reducer function.](/learn/extracting-state-logic-into-a-reducer)
19
+
*[`useState`](/reference/react/useState)объявляет переменную состояния, которую вы можете обновлять напрямую.
20
+
*[`useReducer`](/reference/react/useReducer)объявляет переменную состояния с логикой обновления внутри [функции-редьюсера.](/learn/extracting-state-logic-into-a-reducer)
21
21
22
22
```js
23
23
functionImageGallery() {
@@ -27,11 +27,11 @@ function ImageGallery() {
27
27
28
28
---
29
29
30
-
## Context Hooks {/*context-hooks*/}
30
+
## Хуки контекста {/*context-hooks*/}
31
31
32
-
*Context* lets a component [receive information from distant parents without passing it as props.](/learn/passing-props-to-a-component) For example, your app's top-level component can pass the current UI theme to all components below, no matter how deep.
32
+
*Контекст* позволяет компоненту [получать информацию от удаленных родительских компонентов, не передавая ее через пропсы.](/learn/passing-props-to-a-component) Например, компонент верхнего уровня вашего приложения может передавать текущую тему интерфейса всем компонентам ниже, независимо от их глубины.
33
33
34
-
* [`useContext`](/reference/react/useContext) reads and subscribes to a context.
34
+
* [`useContext`](/reference/react/useContext) считывает контекст и подписывается на него.
35
35
36
36
```js
37
37
functionButton() {
@@ -41,12 +41,12 @@ function Button() {
41
41
42
42
---
43
43
44
-
## Ref Hooks {/*ref-hooks*/}
44
+
## Хуки рефов {/*ref-hooks*/}
45
45
46
-
*Refs* let a component [hold some information that isn't used for rendering,](/learn/referencing-values-with-refs) like a DOM node or a timeout ID. Unlike with state, updating a ref does not re-render your component. Refs are an "escape hatch" from the React paradigm. They are useful when you need to work with non-React systems, such as the built-in browser APIs.
46
+
*Рефы* позволяют компоненту [хранить некоторую информацию, которая не используется для рендеринга,](/learn/referencing-values-with-refs) например, DOM-узел или идентификатор таймера. В отличие от состояния, обновление рефа не вызывает повторный рендеринг компонента. Рефы являются "лазейкой" из парадигмы React. Они полезны, когда вам нужно работать с внешними системами, такими как встроенные API браузера.
47
47
48
-
* [`useRef`](/reference/react/useRef) declares a ref. You can hold any value in it, but most often it's used to hold a DOM node.
49
-
* [`useImperativeHandle`](/reference/react/useImperativeHandle) lets you customize the ref exposed by your component. This is rarely used.
48
+
* [`useRef`](/reference/react/useRef) объявляет реф. Вы можете хранить в нем любое значение, но чаще всего он используется для хранения DOM-узла.
49
+
* [`useImperativeHandle`](/reference/react/useImperativeHandle) позволяет настроить реф, предоставляемый вашим компонентом. Это используется редко.
50
50
51
51
```js
52
52
functionForm() {
@@ -56,11 +56,11 @@ function Form() {
56
56
57
57
---
58
58
59
-
## Effect Hooks {/*effect-hooks*/}
59
+
## Хуки эффектов {/*effect-hooks*/}
60
60
61
-
*Effects* let a component [connect to and synchronize with external systems.](/learn/synchronizing-with-effects) This includes dealing with network, browser DOM, animations, widgets written using a different UI library, and other non-React code.
61
+
*Эффекты* позволяют компоненту [подключаться к внешним системам и синхронизироваться с ними.](/learn/synchronizing-with-effects) Это включает работу с сетью, DOM браузера, анимациями, виджетами, написанными с использованием другой библиотеки пользовательского интерфейса, и другим кодом, не относящимся к React.
62
62
63
-
* [`useEffect`](/reference/react/useEffect) connects a component to an external system.
63
+
* [`useEffect`](/reference/react/useEffect) подключает компонент к внешней системе.
64
64
65
65
```js
66
66
functionChatRoom({ roomId }) {
@@ -72,23 +72,23 @@ function ChatRoom({ roomId }) {
72
72
// ...
73
73
```
74
74
75
-
Effects are an "escape hatch" from the React paradigm. Don't use Effects to orchestrate the data flow of your application. If you're not interacting with an external system, [you might not need an Effect.](/learn/you-might-not-need-an-effect)
75
+
Эффекты являются "лазейкой" из парадигмы React. Не используйте эффекты для управления потоком данных вашего приложения. Если вы не взаимодействуете с внешней системой, [вам может не понадобиться эффект.](/learn/you-might-not-need-an-effect)
76
76
77
-
There are two rarely used variations of `useEffect`with differences in timing:
77
+
Существуют две редко используемые вариации `useEffect`с различиями во времени выполнения:
78
78
79
-
* [`useLayoutEffect`](/reference/react/useLayoutEffect) fires before the browser repaints the screen. You can measure layout here.
80
-
* [`useInsertionEffect`](/reference/react/useInsertionEffect) fires before React makes changes to the DOM. Libraries can insert dynamic CSS here.
79
+
* [`useLayoutEffect`](/reference/react/useLayoutEffect) срабатывает до того, как браузер перерисует экран. Здесь вы можете измерять разметку.
80
+
* [`useInsertionEffect`](/reference/react/useInsertionEffect) срабатывает до того, как React внесет изменения в DOM. Библиотеки могут вставлять динамические CSS здесь.
A common way to optimize re-rendering performance is to skip unnecessary work. For example, you can tell React to reuse a cached calculation or to skip a re-render if the data has not changed since the previous render.
86
+
Распространенный способ оптимизации производительности повторного рендеринга — пропуск ненужных вычислений. Например, вы можете указать React повторно использовать кэшированный результат вычислений или пропустить повторный рендеринг, если данные не изменились с момента предыдущего рендеринга.
87
87
88
-
To skip calculations and unnecessary re-rendering, use one of these Hooks:
88
+
Чтобы пропустить вычисления и ненужный повторный рендеринг, используйте один из этих хуков:
89
89
90
-
- [`useMemo`](/reference/react/useMemo) lets you cache the result of an expensive calculation.
91
-
- [`useCallback`](/reference/react/useCallback) lets you cache a function definition before passing it down to an optimized component.
90
+
- [`useMemo`](/reference/react/useMemo) позволяет кэшировать результат дорогостоящего вычисления.
91
+
- [`useCallback`](/reference/react/useCallback) позволяет кэшировать определение функции перед передачей ее оптимизированному компоненту.
Sometimes, you can't skip re-rendering because the screen actually needs to update. In that case, you can improve performance by separating blocking updates that must be synchronous (like typing into an input) from non-blocking updates which don't need to block the user interface (like updating a chart).
100
+
Иногда вы не можете пропустить повторный рендеринг, потому что экран действительно нуждается в обновлении. В этом случае вы можете повысить производительность, разделяя блокирующие обновления, которые должны быть синхронными (например, ввод в поле), и неблокирующие обновления, которые не должны блокировать пользовательский интерфейс (например, обновление диаграммы).
101
101
102
-
To prioritize rendering, use one of these Hooks:
102
+
Чтобы приоритизировать рендеринг, используйте один из этих хуков:
103
103
104
-
- [`useTransition`](/reference/react/useTransition) lets you mark a state transition as non-blocking and allow other updates to interrupt it.
105
-
- [`useDeferredValue`](/reference/react/useDeferredValue) lets you defer updating a non-critical part of the UI and let other parts update first.
104
+
- [`useTransition`](/reference/react/useTransition) позволяет пометить переход состояния как неблокирующий и разрешить другим обновлениям прерывать его.
105
+
- [`useDeferredValue`](/reference/react/useDeferredValue) позволяет отложить обновление некритической части пользовательского интерфейса и позволить другим частям обновиться первыми.
106
106
107
107
---
108
108
109
-
## Other Hooks {/*other-hooks*/}
109
+
## Другие хуки {/*other-hooks*/}
110
110
111
-
These Hooks are mostly useful to library authors and aren't commonly used in the application code.
111
+
Эти хуки в основном полезны авторам библиотек и редко используются в коде приложений.
112
112
113
-
- [`useDebugValue`](/reference/react/useDebugValue) lets you customize the label React DevTools displays for your custom Hook.
114
-
- [`useId`](/reference/react/useId) lets a component associate a unique ID with itself. Typically used with accessibility APIs.
115
-
- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) lets a component subscribe to an external store.
116
-
* [`useActionState`](/reference/react/useActionState) allows you to manage state of actions.
113
+
- [`useDebugValue`](/reference/react/useDebugValue) позволяет настроить метку, которую React DevTools отображает для вашего пользовательского хука.
114
+
- [`useId`](/reference/react/useId) позволяет компоненту связать с собой уникальный идентификатор. Обычно используется с API доступности.
115
+
- [`useSyncExternalStore`](/reference/react/useSyncExternalStore) позволяет компоненту подписываться на внешний источник данных.
116
+
* [`useActionState`](/reference/react/useActionState) позволяет управлять состоянием действий.
117
117
118
118
---
119
119
120
-
## Your own Hooks {/*your-own-hooks*/}
120
+
## Ваши собственные хуки {/*your-own-hooks*/}
121
121
122
-
You can also [define your own custom Hooks](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) as JavaScript functions.
122
+
Вы также можете [определить свои собственные пользовательские хуки](/learn/reusing-logic-with-custom-hooks#extracting-your-own-custom-hook-from-a-component) в виде функций JavaScript.
0 commit comments