Browse Source

Terminology: Lifecycle hooks -> Lifecycle methods (#1237)

main
Dan Abramov 6 years ago
committed by GitHub
parent
commit
425cb9a429
No known key found for this signature in database GPG Key ID: 4AEE18F83AFDEB23
  1. 8
      content/blog/2016-07-13-mixins-considered-harmful.md
  2. 2
      content/blog/2017-07-26-error-handling-in-react-16.md
  3. 2
      content/docs/addons-animation.md
  4. 4
      content/docs/addons-perf.md
  5. 6
      content/docs/design-principles.md
  6. 4
      content/docs/error-boundaries.md
  7. 2
      content/docs/getting-started.md
  8. 12
      content/docs/implementation-notes.md
  9. 8
      content/docs/integrating-with-other-libraries.md
  10. 2
      content/docs/reference-react-component.md
  11. 2
      content/docs/refs-and-the-dom.md
  12. 12
      content/docs/state-and-lifecycle.md

8
content/blog/2016-07-13-mixins-considered-harmful.md

@ -374,7 +374,7 @@ function withSubscription(WrappedComponent) {
} }
// Optional change: convert CommentList to a function component // Optional change: convert CommentList to a function component
// because it doesn't use lifecycle hooks or state. // because it doesn't use lifecycle methods or state.
function CommentList(props) { function CommentList(props) {
var comments = props.comments; var comments = props.comments;
return ( return (
@ -442,7 +442,7 @@ If you see rendering logic inside a mixin, it’s time to extract a component!
Instead of `RowMixin`, we will define a `<RowHeader>` component. We will also replace the convention of defining a `getHeaderText()` method with the standard mechanism of top-data flow in React: passing props. Instead of `RowMixin`, we will define a `<RowHeader>` component. We will also replace the convention of defining a `getHeaderText()` method with the standard mechanism of top-data flow in React: passing props.
Finally, since neither of those components currently need lifecycle hooks or state, we can declare them as simple functions: Finally, since neither of those components currently need lifecycle methods or state, we can declare them as simple functions:
```js ```js
function RowHeader(props) { function RowHeader(props) {
@ -467,7 +467,7 @@ Props keep component dependencies explicit, easy to replace, and enforceable wit
> **Note:** > **Note:**
> >
> Defining components as functions is not required. There is also nothing wrong with using lifecycle hooks and state—they are first-class React features. We use function components in this example because they are easier to read and we didn’t need those extra features, but classes would work just as fine. > Defining components as functions is not required. There is also nothing wrong with using lifecycle methods and state—they are first-class React features. We use function components in this example because they are easier to read and we didn’t need those extra features, but classes would work just as fine.
### Context ### Context
@ -605,7 +605,7 @@ var Button = React.createClass({
### Other Use Cases ### Other Use Cases
Sometimes people use mixins to selectively add logging to lifecycle hooks in some components. In the future, we intend to provide an [official DevTools API](https://github.com/facebook/react/issues/5306) that would let you implement something similar without touching the components. However it’s still very much a work in progress. If you heavily depend on logging mixins for debugging, you might want to keep using those mixins for a little longer. Sometimes people use mixins to selectively add logging to lifecycle methods in some components. In the future, we intend to provide an [official DevTools API](https://github.com/facebook/react/issues/5306) that would let you implement something similar without touching the components. However it’s still very much a work in progress. If you heavily depend on logging mixins for debugging, you might want to keep using those mixins for a little longer.
If you can’t accomplish something with a component, a higher-order component, or a utility module, it could be mean that React should provide this out of the box. [File an issue](https://github.com/facebook/react/issues/new) to tell us about your use case for mixins, and we’ll help you consider alternatives or perhaps implement your feature request. If you can’t accomplish something with a component, a higher-order component, or a utility module, it could be mean that React should provide this out of the box. [File an issue](https://github.com/facebook/react/issues/new) to tell us about your use case for mixins, and we’ll help you consider alternatives or perhaps implement your feature request.

2
content/blog/2017-07-26-error-handling-in-react-16.md

@ -105,7 +105,7 @@ However, React components are declarative and specify *what* should be rendered:
<Button /> <Button />
``` ```
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` hook caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary. Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` method caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
## Naming Changes from React 15 ## Naming Changes from React 15

2
content/docs/addons-animation.md

@ -234,7 +234,7 @@ import ReactTransitionGroup from 'react-addons-transition-group' // ES6
var ReactTransitionGroup = require('react-addons-transition-group') // ES5 with npm var ReactTransitionGroup = require('react-addons-transition-group') // ES5 with npm
``` ```
`ReactTransitionGroup` is the basis for animations. When children are declaratively added or removed from it (as in the [example above](#getting-started)), special lifecycle hooks are called on them. `ReactTransitionGroup` is the basis for animations. When children are declaratively added or removed from it (as in the [example above](#getting-started)), special lifecycle methods are called on them.
- [`componentWillAppear()`](#componentwillappear) - [`componentWillAppear()`](#componentwillappear)
- [`componentDidAppear()`](#componentdidappear) - [`componentDidAppear()`](#componentdidappear)

4
content/docs/addons-perf.md

@ -20,9 +20,9 @@ var Perf = require('react-addons-perf'); // ES5 with npm
## Overview ## Overview
React is usually quite fast out of the box. However, in situations where you need to squeeze every ounce of performance out of your app, it provides a [shouldComponentUpdate()](/docs/react-component.html#shouldcomponentupdate) hook where you can add optimization hints to React's diff algorithm. React is usually quite fast out of the box. However, in situations where you need to squeeze every ounce of performance out of your app, it provides a [shouldComponentUpdate()](/docs/react-component.html#shouldcomponentupdate) method where you can add optimization hints to React's diff algorithm.
In addition to giving you an overview of your app's overall performance, `Perf` is a profiling tool that tells you exactly where you need to put these hooks. In addition to giving you an overview of your app's overall performance, `Perf` is a profiling tool that tells you exactly where you need to put these methods.
See these articles for an introduction to React performance tooling: See these articles for an introduction to React performance tooling:

6
content/docs/design-principles.md

@ -22,7 +22,7 @@ The key feature of React is composition of components. Components written by dif
For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary. For example, it should be possible to introduce some local state into a component without changing any of the components using it. Similarly, it should be possible to add some initialization and teardown code to any component when necessary.
There is nothing "bad" about using state or lifecycle hooks in components. Like any powerful feature, they should be used in moderation, but we have no intention to remove them. On the contrary, we think they are integral parts of what makes React useful. We might enable [more functional patterns](https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State) in the future, but both local state and lifecycle hooks will be a part of that model. There is nothing "bad" about using state or lifecycle methods in components. Like any powerful feature, they should be used in moderation, but we have no intention to remove them. On the contrary, we think they are integral parts of what makes React useful. We might enable [more functional patterns](https://github.com/reactjs/react-future/tree/master/07%20-%20Returning%20State) in the future, but both local state and lifecycle methods will be a part of that model.
Components are often described as "just functions" but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like [Relay](http://facebook.github.io/relay/) augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form. Components are often described as "just functions" but in our view they need to be more than that to be useful. In React, components describe any composable behavior, and this includes rendering, lifecycle, and state. Some external libraries like [Relay](http://facebook.github.io/relay/) augment components with other responsibilities such as describing data dependencies. It is possible that those ideas might make it back into React too in some form.
@ -30,9 +30,9 @@ Components are often described as "just functions" but in our view they need to
In general we [resist adding features](https://www.youtube.com/watch?v=4anAwXYqLG8) that can be implemented in userland. We don't want to bloat your apps with useless library code. However, there are exceptions to this. In general we [resist adding features](https://www.youtube.com/watch?v=4anAwXYqLG8) that can be implemented in userland. We don't want to bloat your apps with useless library code. However, there are exceptions to this.
For example, if React didn't provide support for local state or lifecycle hooks, people would create custom abstractions for them. When there are multiple abstractions competing, React can't enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator. For example, if React didn't provide support for local state or lifecycle methods, people would create custom abstractions for them. When there are multiple abstractions competing, React can't enforce or take advantage of the properties of either of them. It has to work with the lowest common denominator.
This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don't do it lightly. When we do it, it's because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle hooks, cross-browser event normalization are good examples of this. This is why sometimes we add features to React itself. If we notice that many components implement a certain feature in incompatible or inefficient ways, we might prefer to bake it into React. We don't do it lightly. When we do it, it's because we are confident that raising the abstraction level benefits the whole ecosystem. State, lifecycle methods, cross-browser event normalization are good examples of this.
We always discuss such improvement proposals with the community. You can find some of those discussions by the ["big picture"](https://github.com/facebook/react/issues?q=is:open+is:issue+label:"Type:+Big+Picture") label on the React issue tracker. We always discuss such improvement proposals with the community. You can find some of those discussions by the ["big picture"](https://github.com/facebook/react/issues?q=is:open+is:issue+label:"Type:+Big+Picture") label on the React issue tracker.

4
content/docs/error-boundaries.md

@ -140,13 +140,13 @@ However, React components are declarative and specify *what* should be rendered:
<Button /> <Button />
``` ```
Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` hook caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary. Error boundaries preserve the declarative nature of React, and behave as you would expect. For example, even if an error occurs in a `componentDidUpdate` method caused by a `setState` somewhere deep in the tree, it will still correctly propagate to the closest error boundary.
## How About Event Handlers? ## How About Event Handlers?
Error boundaries **do not** catch errors inside event handlers. Error boundaries **do not** catch errors inside event handlers.
React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle hooks, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen. React doesn't need error boundaries to recover from errors in event handlers. Unlike the render method and lifecycle methods, the event handlers don't happen during rendering. So if they throw, React still knows what to display on the screen.
If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement: If you need to catch an error inside event handler, use the regular JavaScript `try` / `catch` statement:

2
content/docs/getting-started.md

@ -103,7 +103,7 @@ Once you're comfortable with the [main concepts](#main-concepts) and played with
### API Reference ### API Reference
This documentation section is useful when you want to learn more details about a particular React API. For example, [`React.Component` API reference](/docs/react-component.html) can provide you with details on how `setState()` works, and what different lifecycle hooks are useful for. This documentation section is useful when you want to learn more details about a particular React API. For example, [`React.Component` API reference](/docs/react-component.html) can provide you with details on how `setState()` works, and what different lifecycle methods are useful for.
### Glossary and FAQ ### Glossary and FAQ

12
content/docs/implementation-notes.md

@ -434,7 +434,7 @@ mountTree(<App />, rootEl);
### Unmounting ### Unmounting
Now that we have internal instances that hold onto their children and the DOM nodes, we can implement unmounting. For a composite component, unmounting calls a lifecycle hook and recurses. Now that we have internal instances that hold onto their children and the DOM nodes, we can implement unmounting. For a composite component, unmounting calls a lifecycle method and recurses.
```js ```js
class CompositeComponent { class CompositeComponent {
@ -442,7 +442,7 @@ class CompositeComponent {
// ... // ...
unmount() { unmount() {
// Call the lifecycle hook if necessary // Call the lifecycle method if necessary
var publicInstance = this.publicInstance; var publicInstance = this.publicInstance;
if (publicInstance) { if (publicInstance) {
if (publicInstance.componentWillUnmount) { if (publicInstance.componentWillUnmount) {
@ -514,7 +514,7 @@ function mountTree(element, containerNode) {
} }
``` ```
Now, running `unmountTree()`, or running `mountTree()` repeatedly, removes the old tree and runs the `componentWillUnmount()` lifecycle hook on components. Now, running `unmountTree()`, or running `mountTree()` repeatedly, removes the old tree and runs the `componentWillUnmount()` lifecycle method on components.
### Updating ### Updating
@ -554,7 +554,7 @@ This is the part that is often described as "virtual DOM diffing" although what
### Updating Composite Components ### Updating Composite Components
When a composite component receives a new element, we run the `componentWillUpdate()` lifecycle hook. When a composite component receives a new element, we run the `componentWillUpdate()` lifecycle method.
Then we re-render the component with the new props, and get the next rendered element: Then we re-render the component with the new props, and get the next rendered element:
@ -868,9 +868,9 @@ This document is simplified compared to the real codebase. There are a few impor
* The reconciler also takes care of attaching and detaching refs to composite components and host nodes. * The reconciler also takes care of attaching and detaching refs to composite components and host nodes.
* Lifecycle hooks that are called after the DOM is ready, such as `componentDidMount()` and `componentDidUpdate()`, get collected into "callback queues" and are executed in a single batch. * Lifecycle methods that are called after the DOM is ready, such as `componentDidMount()` and `componentDidUpdate()`, get collected into "callback queues" and are executed in a single batch.
* React puts information about the current update into an internal object called "transaction". Transactions are useful for keeping track of the queue of pending lifecycle hooks, the current DOM nesting for the warnings, and anything else that is "global" to a specific update. Transactions also ensure React "cleans everything up" after updates. For example, the transaction class provided by React DOM restores the input selection after any update. * React puts information about the current update into an internal object called "transaction". Transactions are useful for keeping track of the queue of pending lifecycle methods, the current DOM nesting for the warnings, and anything else that is "global" to a specific update. Transactions also ensure React "cleans everything up" after updates. For example, the transaction class provided by React DOM restores the input selection after any update.
### Jumping into the Code ### Jumping into the Code

8
content/docs/integrating-with-other-libraries.md

@ -39,7 +39,7 @@ class SomePlugin extends React.Component {
} }
``` ```
Note that we defined both `componentDidMount` and `componentWillUnmount` [lifecycle hooks](/docs/react-component.html#the-component-lifecycle). Many jQuery plugins attach event listeners to the DOM so it's important to detach them in `componentWillUnmount`. If the plugin does not provide a method for cleanup, you will probably have to provide your own, remembering to remove any event listeners the plugin registered to prevent memory leaks. Note that we defined both `componentDidMount` and `componentWillUnmount` [lifecycle methods](/docs/react-component.html#the-component-lifecycle). Many jQuery plugins attach event listeners to the DOM so it's important to detach them in `componentWillUnmount`. If the plugin does not provide a method for cleanup, you will probably have to provide your own, remembering to remove any event listeners the plugin registered to prevent memory leaks.
### Integrating with jQuery Chosen Plugin ### Integrating with jQuery Chosen Plugin
@ -87,7 +87,7 @@ class Chosen extends React.Component {
Notice how we wrapped `<select>` in an extra `<div>`. This is necessary because Chosen will append another DOM element right after the `<select>` node we passed to it. However, as far as React is concerned, `<div>` always only has a single child. This is how we ensure that React updates won't conflict with the extra DOM node appended by Chosen. It is important that if you modify the DOM outside of React flow, you must ensure React doesn't have a reason to touch those DOM nodes. Notice how we wrapped `<select>` in an extra `<div>`. This is necessary because Chosen will append another DOM element right after the `<select>` node we passed to it. However, as far as React is concerned, `<div>` always only has a single child. This is how we ensure that React updates won't conflict with the extra DOM node appended by Chosen. It is important that if you modify the DOM outside of React flow, you must ensure React doesn't have a reason to touch those DOM nodes.
Next, we will implement the lifecycle hooks. We need to initialize Chosen with the ref to the `<select>` node in `componentDidMount`, and tear it down in `componentWillUnmount`: Next, we will implement the lifecycle methods. We need to initialize Chosen with the ref to the `<select>` node in `componentDidMount`, and tear it down in `componentWillUnmount`:
```js{2,3,7} ```js{2,3,7}
componentDidMount() { componentDidMount() {
@ -135,7 +135,7 @@ handleChange(e) {
Finally, there is one more thing left to do. In React, props can change over time. For example, the `<Chosen>` component can get different children if parent component's state changes. This means that at integration points it is important that we manually update the DOM in response to prop updates, since we no longer let React manage the DOM for us. Finally, there is one more thing left to do. In React, props can change over time. For example, the `<Chosen>` component can get different children if parent component's state changes. This means that at integration points it is important that we manually update the DOM in response to prop updates, since we no longer let React manage the DOM for us.
Chosen's documentation suggests that we can use jQuery `trigger()` API to notify it about changes to the original DOM element. We will let React take care of updating `this.props.children` inside `<select>`, but we will also add a `componentDidUpdate()` lifecycle hook that notifies Chosen about changes in the children list: Chosen's documentation suggests that we can use jQuery `trigger()` API to notify it about changes to the original DOM element. We will let React take care of updating `this.props.children` inside `<select>`, but we will also add a `componentDidUpdate()` lifecycle method that notifies Chosen about changes in the children list:
```js{2,3} ```js{2,3}
componentDidUpdate(prevProps) { componentDidUpdate(prevProps) {
@ -436,4 +436,4 @@ ReactDOM.render(
[**Try it on CodePen**](http://codepen.io/gaearon/pen/PmWwwa?editors=0010) [**Try it on CodePen**](http://codepen.io/gaearon/pen/PmWwwa?editors=0010)
This technique is not limited to Backbone. You can use React with any model library by subscribing to its changes in the lifecycle hooks and, optionally, copying the data into the local React state. This technique is not limited to Backbone. You can use React with any model library by subscribing to its changes in the lifecycle methods and, optionally, copying the data into the local React state.

2
content/docs/reference-react-component.md

@ -343,7 +343,7 @@ UNSAFE_componentWillMount()
Avoid introducing any side-effects or subscriptions in this method. For those use cases, use `componentDidMount()` instead. Avoid introducing any side-effects or subscriptions in this method. For those use cases, use `componentDidMount()` instead.
This is the only lifecycle hook called on server rendering. This is the only lifecycle method called on server rendering.
> Note > Note
> >

2
content/docs/refs-and-the-dom.md

@ -105,7 +105,7 @@ class CustomTextInput extends React.Component {
} }
``` ```
React will assign the `current` property with the DOM element when the component mounts, and assign it back to `null` when it unmounts. `ref` updates happen before `componentDidMount` or `componentDidUpdate` lifecycle hooks. React will assign the `current` property with the DOM element when the component mounts, and assign it back to `null` when it unmounts. `ref` updates happen before `componentDidMount` or `componentDidUpdate` lifecycle methods.
#### Adding a Ref to a Class Component #### Adding a Ref to a Class Component

12
content/docs/state-and-lifecycle.md

@ -105,7 +105,7 @@ class Clock extends React.Component {
`Clock` is now defined as a class rather than a function. `Clock` is now defined as a class rather than a function.
The `render` method will be called each time an update happens, but as long as we render `<Clock />` into the same DOM node, only a single instance of the `Clock` class will be used. This lets us use additional features such as local state and lifecycle hooks. The `render` method will be called each time an update happens, but as long as we render `<Clock />` into the same DOM node, only a single instance of the `Clock` class will be used. This lets us use additional features such as local state and lifecycle methods.
## Adding Local State to a Class ## Adding Local State to a Class
@ -233,9 +233,9 @@ class Clock extends React.Component {
} }
``` ```
These methods are called "lifecycle hooks". These methods are called "lifecycle methods".
The `componentDidMount()` hook runs after the component output has been rendered to the DOM. This is a good place to set up a timer: The `componentDidMount()` method runs after the component output has been rendered to the DOM. This is a good place to set up a timer:
```js{2-5} ```js{2-5}
componentDidMount() { componentDidMount() {
@ -250,7 +250,7 @@ Note how we save the timer ID right on `this`.
While `this.props` is set up by React itself and `this.state` has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID). While `this.props` is set up by React itself and `this.state` has a special meaning, you are free to add additional fields to the class manually if you need to store something that doesn’t participate in the data flow (like a timer ID).
We will tear down the timer in the `componentWillUnmount()` lifecycle hook: We will tear down the timer in the `componentWillUnmount()` lifecycle method:
```js{2} ```js{2}
componentWillUnmount() { componentWillUnmount() {
@ -312,11 +312,11 @@ Let's quickly recap what's going on and the order in which the methods are calle
2) React then calls the `Clock` component's `render()` method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the `Clock`'s render output. 2) React then calls the `Clock` component's `render()` method. This is how React learns what should be displayed on the screen. React then updates the DOM to match the `Clock`'s render output.
3) When the `Clock` output is inserted in the DOM, React calls the `componentDidMount()` lifecycle hook. Inside it, the `Clock` component asks the browser to set up a timer to call the component's `tick()` method once a second. 3) When the `Clock` output is inserted in the DOM, React calls the `componentDidMount()` lifecycle method. Inside it, the `Clock` component asks the browser to set up a timer to call the component's `tick()` method once a second.
4) Every second the browser calls the `tick()` method. Inside it, the `Clock` component schedules a UI update by calling `setState()` with an object containing the current time. Thanks to the `setState()` call, React knows the state has changed, and calls the `render()` method again to learn what should be on the screen. This time, `this.state.date` in the `render()` method will be different, and so the render output will include the updated time. React updates the DOM accordingly. 4) Every second the browser calls the `tick()` method. Inside it, the `Clock` component schedules a UI update by calling `setState()` with an object containing the current time. Thanks to the `setState()` call, React knows the state has changed, and calls the `render()` method again to learn what should be on the screen. This time, `this.state.date` in the `render()` method will be different, and so the render output will include the updated time. React updates the DOM accordingly.
5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle hook so the timer is stopped. 5) If the `Clock` component is ever removed from the DOM, React calls the `componentWillUnmount()` lifecycle method so the timer is stopped.
## Using State Correctly ## Using State Correctly

Loading…
Cancel
Save