Skip to content

[fix] Sync with reactjs.org @ 1f2dbb7a #286

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Apr 1, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
78 changes: 11 additions & 67 deletions content/docs/hooks-faq.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ prev: hooks-reference.html
).join('\n')
-->

<<<<<<< HEAD
* [Внедрение хуков](#adoption-strategy)
* [В какой версии React появились хуки?](#which-versions-of-react-include-hooks)
* [Нужно ли переписать все мои классовые компоненты?](#do-i-need-to-rewrite-all-my-class-components)
Expand All @@ -42,6 +41,7 @@ prev: hooks-reference.html
* [Как я могу реализовать `getDerivedStateFromProps`?](#how-do-i-implement-getderivedstatefromprops)
* [Существует что-нибудь наподобие forceUpdate?](#is-there-something-like-forceupdate)
* [Могу ли я изменить реф, переданный в функциональный компонент?](#can-i-make-a-ref-to-a-function-component)
* [Как я могу измерить узел DOM?](#how-can-i-measure-a-dom-node)
* [Что значит `const [thing, setThing] = useState()`?](#what-does-const-thing-setthing--usestate-mean)
* [Оптимизации производительности](#performance-optimizations)
* [Могу ли я пропустить эффект при обновлениях?](#can-i-skip-an-effect-on-updates)
Expand All @@ -62,52 +62,6 @@ prev: hooks-reference.html
### В какой версии React появились хуки? {#which-versions-of-react-include-hooks}

Начиная с релиза 16.8.0, React включает в себя стабильную реализацию хуков для:
=======
* **[Adoption Strategy](#adoption-strategy)**
* [Which versions of React include Hooks?](#which-versions-of-react-include-hooks)
* [Do I need to rewrite all my class components?](#do-i-need-to-rewrite-all-my-class-components)
* [What can I do with Hooks that I couldn't with classes?](#what-can-i-do-with-hooks-that-i-couldnt-with-classes)
* [How much of my React knowledge stays relevant?](#how-much-of-my-react-knowledge-stays-relevant)
* [Should I use Hooks, classes, or a mix of both?](#should-i-use-hooks-classes-or-a-mix-of-both)
* [Do Hooks cover all use cases for classes?](#do-hooks-cover-all-use-cases-for-classes)
* [Do Hooks replace render props and higher-order components?](#do-hooks-replace-render-props-and-higher-order-components)
* [What do Hooks mean for popular APIs like Redux connect() and React Router?](#what-do-hooks-mean-for-popular-apis-like-redux-connect-and-react-router)
* [Do Hooks work with static typing?](#do-hooks-work-with-static-typing)
* [How to test components that use Hooks?](#how-to-test-components-that-use-hooks)
* [What exactly do the lint rules enforce?](#what-exactly-do-the-lint-rules-enforce)
* **[From Classes to Hooks](#from-classes-to-hooks)**
* [How do lifecycle methods correspond to Hooks?](#how-do-lifecycle-methods-correspond-to-hooks)
* [How can I do data fetching with Hooks?](#how-can-i-do-data-fetching-with-hooks)
* [Is there something like instance variables?](#is-there-something-like-instance-variables)
* [Should I use one or many state variables?](#should-i-use-one-or-many-state-variables)
* [Can I run an effect only on updates?](#can-i-run-an-effect-only-on-updates)
* [How to get the previous props or state?](#how-to-get-the-previous-props-or-state)
* [Why am I seeing stale props or state inside my function?](#why-am-i-seeing-stale-props-or-state-inside-my-function)
* [How do I implement getDerivedStateFromProps?](#how-do-i-implement-getderivedstatefromprops)
* [Is there something like forceUpdate?](#is-there-something-like-forceupdate)
* [Can I make a ref to a function component?](#can-i-make-a-ref-to-a-function-component)
* [How can I measure a DOM node?](#how-can-i-measure-a-dom-node)
* [What does const [thing, setThing] = useState() mean?](#what-does-const-thing-setthing--usestate-mean)
* **[Performance Optimizations](#performance-optimizations)**
* [Can I skip an effect on updates?](#can-i-skip-an-effect-on-updates)
* [Is it safe to omit functions from the list of dependencies?](#is-it-safe-to-omit-functions-from-the-list-of-dependencies)
* [What can I do if my effect dependencies change too often?](#what-can-i-do-if-my-effect-dependencies-change-too-often)
* [How do I implement shouldComponentUpdate?](#how-do-i-implement-shouldcomponentupdate)
* [How to memoize calculations?](#how-to-memoize-calculations)
* [How to create expensive objects lazily?](#how-to-create-expensive-objects-lazily)
* [Are Hooks slow because of creating functions in render?](#are-hooks-slow-because-of-creating-functions-in-render)
* [How to avoid passing callbacks down?](#how-to-avoid-passing-callbacks-down)
* [How to read an often-changing value from useCallback?](#how-to-read-an-often-changing-value-from-usecallback)
* **[Under the Hood](#under-the-hood)**
* [How does React associate Hook calls with components?](#how-does-react-associate-hook-calls-with-components)
* [What is the prior art for Hooks?](#what-is-the-prior-art-for-hooks)

## Adoption Strategy {#adoption-strategy}

### Which versions of React include Hooks? {#which-versions-of-react-include-hooks}

Starting with 16.8.0, React includes a stable implementation of React Hooks for:
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a

* React DOM
* React DOM Server
Expand Down Expand Up @@ -450,7 +404,7 @@ function Example() {

Если вы намеренно хотите считать из асинхронного колбэка *свежайшее* состояние, вы можете сперва сохранить его [в реф](/docs/hooks-faq.html#is-there-something-like-instance-variables), потом изменить его и затем считать его из рефа.

Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
Наконец, возможна другая ситуация, почему вы видите устаревшие пропсы или состояние: когда вы используете оптимизацию с помощью «массива зависимостей», но неправильно указали какие-то зависимости. Например, если эффект передаёт вторым параметром `[]`, но при этом использует `someProp`, то он продолжит «видеть» исходное значение `someProp`. Правильным решением является либо исправление массива, либо отказ от его использования.
По этим ссылкам описаны [подходы к функциям](#is-it-safe-to-omit-functions-from-the-list-of-dependencies) в аналогичных ситуациях и [другие известные способы](#what-can-i-do-if-my-effect-dependencies-change-too-often) снижения частоты вызова эффектов, исключающие передачу неправильных зависимостей.

>Примечание
Expand Down Expand Up @@ -498,15 +452,11 @@ function ScrollView({row}) {

### Могу ли я изменить реф, переданный в функциональный компонент? {#can-i-make-a-ref-to-a-function-component}


Несмотря на то, что вам не понадобится это часто, вы можете предоставить некоторые императивные методы родительскому компоненту, используя хук [`useImperativeHandle`](/docs/hooks-reference.html#useimperativehandle).

<<<<<<< HEAD
### Что значит `const [thing, setThing] = useState()`? {#what-does-const-thing-setthing--usestate-mean}
=======
### How can I measure a DOM node? {#how-can-i-measure-a-dom-node}
### Как я могу измерить узел DOM? {#how-can-i-measure-a-dom-node}

In order to measure the position or size of a DOM node, you can use a [callback ref](/docs/refs-and-the-dom.html#callback-refs). React will call that callback whenever the ref gets attached to a different node. Here is a [small demo](https://codesandbox.io/s/l7m0v5x4v9):
Для измерения положения или размера узла DOM можно использовать [колбэк-реф](/docs/refs-and-the-dom.html#callback-refs). React будет вызывать этот колбэк всякий раз, когда ref подключается к другому узлу. Вот [небольшая демонстрация](https://codesandbox.io/s/l7m0v5x4v9):

```js{4-8,12}
function MeasureExample() {
Expand All @@ -520,18 +470,18 @@ function MeasureExample() {

return (
<>
<h1 ref={measuredRef}>Hello, world</h1>
<h2>The above header is {Math.round(height)}px tall</h2>
<h1 ref={measuredRef}>Привет, мир</h1>
<h2>Заголовок выше {Math.round(height)} пикселей в высоту</h2>
</>
);
}
```

We didn't choose `useRef` in this example because an object ref doesn't notify us about *changes* to the current ref value. Using a callback ref ensures that [even if a child component displays the measured node later](https://codesandbox.io/s/818zzk8m78) (e.g. in response to a click), we still get notified about it in the parent component and can update the measurements.
Мы не выбрали `useRef` в этом примере, потому что объект рефа не уведомляет нас об *изменениях* текущего значения рефа. Использование колбэк-рефа гарантирует, что [даже если дочерний компонент отображает измеренный узел позже](https://codesandbox.io/s/818zzk8m78) (например, в ответ на клик), мы по-прежнему получаем уведомление об этом в родительском компоненте и можем обновлять измерения.

Note that we pass `[]` as a dependency array to `useCallback`. This ensures that our ref callback doesn't change between the re-renders, and so React won't call it unnecessarily.
Обратите внимание, что мы передаем `[]` как массив зависимостей в `useCallback`. Это гарантирует, что наш обратный вызов рефа не изменится между повторными рендерами, и поэтому React не вызовет его без необходимости.

If you want, you can [extract this logic](https://codesandbox.io/s/m5o42082xy) into a reusable Hook:
При желании вы можете [извлечь эту логику](https://codesandbox.io/s/m5o42082xy) в многоразовый хук:

```js{2}
function MeasureExample() {
Expand All @@ -558,8 +508,7 @@ function useClientRect() {
```


### What does `const [thing, setThing] = useState()` mean? {#what-does-const-thing-setthing--usestate-mean}
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
### Что значит `const [thing, setThing] = useState()`? {#what-does-const-thing-setthing--usestate-mean}

Если вы не знакомы с этим синтаксисом, ознакомьтесь с [объяснением](/docs/hooks-state.html#tip-what-do-square-brackets-mean) в документации хука состояния.

Expand Down Expand Up @@ -962,13 +911,8 @@ function Form() {
const [text, updateText] = useState('');
const textRef = useRef();

<<<<<<< HEAD
useLayoutEffect(() => {
textRef.current = text; // Записать в реф
=======
useEffect(() => {
textRef.current = text; // Write it to the ref
>>>>>>> 1f2dbb7a4f531d1c9d70ae69e025eac992b37c6a
textRef.current = text; // Записать это в реф
});

const handleSubmit = useCallback(() => {
Expand Down
Loading