From a2360a9c8f21bde5751688e1676e6a6a9814bb6e Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Tue, 4 Oct 2016 20:02:36 +0100 Subject: [PATCH 1/4] Fix the conflict --- docs/_layouts/default.html | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/docs/_layouts/default.html b/docs/_layouts/default.html index 67081b18c31d9..ec28765ce5127 100644 --- a/docs/_layouts/default.html +++ b/docs/_layouts/default.html @@ -74,13 +74,9 @@
-<<<<<<< HEAD - Get Started - Take the Tutorial -======= + Get Started - Download React v{{site.react_version}} ->>>>>>> 46983cf36c2e2b7e5eeae4f76273cd0daf299b7e + Take the Tutorial
From cc7b3a9b6389f32bd4a631c0771fc16955f4bbdd Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Mon, 10 Oct 2016 09:33:50 -0700 Subject: [PATCH 2/4] Merge Component Lifecycle guide into React.Component reference, and create React without ES6 Guide --- docs/docs-old/05-reusable-components.md | 197 +-------------------- docs/docs/react-without-es6.md | 221 ++++++++++++++++++++++++ docs/docs/reference-react-component.md | 115 ++++++++++-- 3 files changed, 327 insertions(+), 206 deletions(-) create mode 100644 docs/docs/react-without-es6.md diff --git a/docs/docs-old/05-reusable-components.md b/docs/docs-old/05-reusable-components.md index 640460a114333..4bf562dec6620 100644 --- a/docs/docs-old/05-reusable-components.md +++ b/docs/docs-old/05-reusable-components.md @@ -255,7 +255,7 @@ class Greeting extends React.Component { } ``` -If you don't use ES6 yet, you may use [`React.createClass`](/react/docs/top-level-api.html#react.createclass) helper instead: +If you don't use ES6 yet, you may use the React.createClass helper instead: ```javascript @@ -266,197 +266,4 @@ var Greeting = React.createClass({ }); ``` -The API of ES6 classes is similar to [`React.createClass`](/react/docs/top-level-api.html#react.createclass) with a few exceptions. - -### Declaring Prop Types and Default Props - -With functions and ES6 classes, `propTypes` and `defaultProps` are defined as properties on the components themselves: - -```javascript -class Greeting extends React.Component { - // ... -} - -Greeting.propTypes = { - name: React.PropTypes.string -}; - -Greeting.defaultProps = { - name: 'Mary' -}; -``` - -With `React.createClass()`, you need to define `propTypes` as a property on the passed object, and `getDefaultProps()` as a function on it: - -```javascript -var Greeting = React.createClass({ - propTypes: { - name: React.PropTypes.string - }, - - getDefaultProps: function() { - return { - name: 'Mary' - }; - }, - - // ... - -}); -``` - -### Setting the Initial State - -In ES6 classes, you can define the initial state by assigning `this.state` in the constructor: - -```javascript -class Counter extends React.Component { - constructor(props) { - super(props); - this.state = {count: props.initialCount}; - } - // ... -} -``` - -With `React.createClass()`, you have to provide a separate `getInitialState` method that returns the initial state: - -```javascript -var Counter = React.createClass({ - getInitialState: function() { - return {count: this.props.initialCount}; - }, - // ... -}); -``` - -### Autobinding - -In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` in the constructor: - -```javascript -class SayHello extends React.Component { - constructor(props) { - super(props); - // This line is important! - this.handleClick = this.handleClick.bind(this); - } - - handleClick() { - alert('Hello!'); - } - - render() { - // Because `this.handleClick` is bound, we can use it as an event handler. - return ( - - ); - } -} -``` - -With `React.createClass()`, this is not necessary because it binds all methods: - -```javascript -var SayHello = React.createClass({ - handleClick: function() { - alert('Hello!'); - }, - - render: function() { - return ( - - ); - } -}); -``` - -This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications. - -If the boilerplate code is too unattractive to you, you may enable the **experimental** [Class Properties](https://babeljs.io/docs/plugins/transform-class-properties/) syntax proposal with Babel: - - -```javascript -class SayHello extends React.Component { - // WARNING: this syntax is experimental! - // Using an arrow here binds the method: - handleClick = () => { - alert('Hello!'); - } - - render() { - return ( - - ); - } -} -``` - -Please note that the syntax above is **experimental** and the syntax may change, or the proposal might not make it into the language. - -If you'd rather play it safe, you have a few options: - -* Bind methods in the constructor. -* Use arrow functions, e.g. `onClick={(e) => this.handleClick(e)})`. -* Keep using `React.createClass()`. - -### Mixins - ->**Note:** -> ->ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. -> ->**We also found numerous issues in codebases using mixins, [and don't recommend using them in the new code](/react/blog/2016/07/13/mixins-considered-harmful.html).** -> ->This section exists only for the reference. - -Sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](https://en.wikipedia.org/wiki/Cross-cutting_concern). [`React.createClass`](/react/docs/top-level-api.html#react.createclass) lets you use a legacy `mixins` system for that. - -One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed. - -```javascript -var SetIntervalMixin = { - componentWillMount: function() { - this.intervals = []; - }, - setInterval: function() { - this.intervals.push(setInterval.apply(null, arguments)); - }, - componentWillUnmount: function() { - this.intervals.forEach(clearInterval); - } -}; - -var TickTock = React.createClass({ - mixins: [SetIntervalMixin], // Use the mixin - getInitialState: function() { - return {seconds: 0}; - }, - componentDidMount: function() { - this.setInterval(this.tick, 1000); // Call a method on the mixin - }, - tick: function() { - this.setState({seconds: this.state.seconds + 1}); - }, - render: function() { - return ( -

- React has been running for {this.state.seconds} seconds. -

- ); - } -}); - -ReactDOM.render( - , - document.getElementById('example') -); -``` - -If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component. +The API of ES6 classes is similar to `React.createClass` with a few exceptions. These are covered in [Using React without ES6](/react/docs/react-without-es6.html). diff --git a/docs/docs/react-without-es6.md b/docs/docs/react-without-es6.md new file mode 100644 index 0000000000000..c620393985ffc --- /dev/null +++ b/docs/docs/react-without-es6.md @@ -0,0 +1,221 @@ +--- +id: react-without-es6 +title: Using React without ES6 +permalink: docs/react-without-es6.html +--- + +Normally you would define a React component as a plain JavaScript class: + +```javascript +class Greeting extends React.Component { + render() { + return

Hello, {this.props.name}

; + } +} +``` + +If you don't use ES6 yet, you may use the `React.createClass` helper instead: + + +```javascript +var Greeting = React.createClass({ + render: function() { + return

Hello, {this.props.name}

; + } +}); +``` + +The API of ES6 classes is similar to `React.createClass` with a few exceptions. + +## Declaring Prop Types and Default Props + +With functions and ES6 classes, `propTypes` and `defaultProps` are defined as properties on the components themselves: + +```javascript +class Greeting extends React.Component { + // ... +} + +Greeting.propTypes = { + name: React.PropTypes.string +}; + +Greeting.defaultProps = { + name: 'Mary' +}; +``` + +With `React.createClass()`, you need to define `propTypes` as a property on the passed object, and `getDefaultProps()` as a function on it: + +```javascript +var Greeting = React.createClass({ + propTypes: { + name: React.PropTypes.string + }, + + getDefaultProps: function() { + return { + name: 'Mary' + }; + }, + + // ... + +}); +``` + +## Setting the Initial State + +In ES6 classes, you can define the initial state by assigning `this.state` in the constructor: + +```javascript +class Counter extends React.Component { + constructor(props) { + super(props); + this.state = {count: props.initialCount}; + } + // ... +} +``` + +With `React.createClass()`, you have to provide a separate `getInitialState` method that returns the initial state: + +```javascript +var Counter = React.createClass({ + getInitialState: function() { + return {count: this.props.initialCount}; + }, + // ... +}); +``` + +## Autobinding + +In React components declared as ES6 classes, methods follow the same semantics as regular ES6 classes. This means that they don't automatically bind `this` to the instance. You'll have to explicitly use `.bind(this)` in the constructor: + +```javascript +class SayHello extends React.Component { + constructor(props) { + super(props); + // This line is important! + this.handleClick = this.handleClick.bind(this); + } + + handleClick() { + alert('Hello!'); + } + + render() { + // Because `this.handleClick` is bound, we can use it as an event handler. + return ( + + ); + } +} +``` + +With `React.createClass()`, this is not necessary because it binds all methods: + +```javascript +var SayHello = React.createClass({ + handleClick: function() { + alert('Hello!'); + }, + + render: function() { + return ( + + ); + } +}); +``` + +This means writing ES6 classes comes with a little more boilerplate code for event handlers, but the upside is slightly better performance in large applications. + +If the boilerplate code is too unattractive to you, you may enable the **experimental** [Class Properties](https://babeljs.io/docs/plugins/transform-class-properties/) syntax proposal with Babel: + + +```javascript +class SayHello extends React.Component { + // WARNING: this syntax is experimental! + // Using an arrow here binds the method: + handleClick = () => { + alert('Hello!'); + } + + render() { + return ( + + ); + } +} +``` + +Please note that the syntax above is **experimental** and the syntax may change, or the proposal might not make it into the language. + +If you'd rather play it safe, you have a few options: + +* Bind methods in the constructor. +* Use arrow functions, e.g. `onClick={(e) => this.handleClick(e)})`. +* Keep using `React.createClass()`. + +## Mixins + +>**Note:** +> +>ES6 launched without any mixin support. Therefore, there is no support for mixins when you use React with ES6 classes. +> +>**We also found numerous issues in codebases using mixins, [and don't recommend using them in the new code](/react/blog/2016/07/13/mixins-considered-harmful.html).** +> +>This section exists only for the reference. + +Sometimes very different components may share some common functionality. These are sometimes called [cross-cutting concerns](https://en.wikipedia.org/wiki/Cross-cutting_concern). [`React.createClass`](/react/docs/top-level-api.html#react.createclass) lets you use a legacy `mixins` system for that. + +One common use case is a component wanting to update itself on a time interval. It's easy to use `setInterval()`, but it's important to cancel your interval when you don't need it anymore to save memory. React provides [lifecycle methods](/react/docs/working-with-the-browser.html#component-lifecycle) that let you know when a component is about to be created or destroyed. Let's create a simple mixin that uses these methods to provide an easy `setInterval()` function that will automatically get cleaned up when your component is destroyed. + +```javascript +var SetIntervalMixin = { + componentWillMount: function() { + this.intervals = []; + }, + setInterval: function() { + this.intervals.push(setInterval.apply(null, arguments)); + }, + componentWillUnmount: function() { + this.intervals.forEach(clearInterval); + } +}; + +var TickTock = React.createClass({ + mixins: [SetIntervalMixin], // Use the mixin + getInitialState: function() { + return {seconds: 0}; + }, + componentDidMount: function() { + this.setInterval(this.tick, 1000); // Call a method on the mixin + }, + tick: function() { + this.setState({seconds: this.state.seconds + 1}); + }, + render: function() { + return ( +

+ React has been running for {this.state.seconds} seconds. +

+ ); + } +}); + +ReactDOM.render( + , + document.getElementById('example') +); +``` + +If a component is using multiple mixins and several mixins define the same lifecycle method (i.e. several mixins want to do some cleanup when the component is destroyed), all of the lifecycle methods are guaranteed to be called. Methods defined on mixins run in the order mixins were listed, followed by a method call on the component. diff --git a/docs/docs/reference-react-component.md b/docs/docs/reference-react-component.md index 39769a9536888..b691684256183 100644 --- a/docs/docs/reference-react-component.md +++ b/docs/docs/reference-react-component.md @@ -6,9 +6,63 @@ category: Reference permalink: docs/react-component.html --- -## React.Component -`React.Component` is an abstract base class, so it rarely makes sense to refer to `React.Component` directly. Instead, you will typically subclass it, and define at least a `render` method. +[Components](/react/docs/components-and-props.html) let you split the UI into independent, reusable pieces, and think about each piece in isolation. + +## Overview + +`React.Component` is an abstract base class, so it rarely makes sense to refer to `React.Component` directly. Instead, you will typically subclass it, and define at least a [`.render()`](#.render) method. + +Normally you would define a React component as a plain JavaScript class: + +```javascript +class Greeting extends React.Component { + render() { + return

Hello, {this.props.name}

; + } +} +``` + +If you don't use ES6 yet, you may use the `React.createClass` helper instead: + +```javascript +var Greeting = React.createClass({ + render: function() { + return

Hello, {this.props.name}

; + } +}); +``` + +The `React.Component` reference assumes the use of ES6. The API for `React.createClass` components is similar with a few exceptions. Take a look at [Using React without ES6](/react/docs/react-without-es6.html) to learn more. + +### The Component Lifecycle + +Components have three main parts of their lifecycle: + +* Mounting: A component is being inserted into the DOM. +* Updating: A component is being re-rendered to determine if the DOM should be updated. +* Unmounting: A component is being removed from the DOM. + +React provides lifecycle methods that you can specify to hook into this process. Methods prefixed with **`will`** are called right before something happens, and methods prefixed with **`did`** are called right after something happens. + +#### Mounting + +React will call [`.componentWillMount()`](#.componentwillmount) and [`.componentDidMount()`](#.componentdidmount) when a component is being inserted into the DOM. + +#### Updating + +State changes can lead to the component being re-rendered. The following methods will be called and are used to determine if the DOM should be updated. + + - [`.componentWillReceiveProps()`](#.componentwillreceivepropsnextprops) is invoked before a mounted component receives new props and can be used to update state in response to prop changes. + - Components will always re-render when the state is updated. Take a look at [`.shouldComponentUpdate(nextProps, nextState)`](#.shouldcomponentupdatenextprops-nextstate) if you need to change the default behavior. + - [`.componentWillUpdate(nextProps, nextState)`](#.componentwillupdatenextprops-nextstate) can be used for preparation before an update occurs. + - [`.componentDidUpdate(prevProps, prevState)`](#.componentdidupdateprevprops-prevstate) is invoked after an update and can be used to operate on the DOM after the component has been updated. + +#### Unmounting + +[`.componentWillUnmount()`](#.componentwillunmount) can be used to perform any cleanup, as it is invoked immediately before a component is unmounted and destroyed. + +## Reference - [`constructor(props)`](#constructor) - [`.componentDidMount()`](#.componentdidmount) @@ -27,6 +81,7 @@ permalink: docs/react-component.html - [`.shouldComponentUpdate(nextProps, nextState)`](#.shouldcomponentupdatenextprops-nextstate) - [`.state`](#.state) + ### `constructor(props)` The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs. @@ -44,27 +99,47 @@ constructor(props) { ### `.componentDidMount()` -TODO +`componentDidMount()` is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering. ### `.componentDidUpdate(prevProps, prevState)` -TODO +`componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render. + +Use this as an opportunity to operate on the DOM when the component has been updated. + +> Note +> +> `componentDidUpdate()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. + ### `.componentWillMount()` -TODO +`componentWillMount()` is invoked immediately before mounting occurs. It is called before `render()`, therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method. + +This is the only lifecycle hook called on server rendering. ### `.componentWillReceiveProps(nextProps)` -TODO +`componentWillReceiveProps()` is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare `this.props` and `nextProps` and perform state transitions using `this.setState()` in this method. + +Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render. + +`componentWillReceiveProps()` is not invoked if you just call `this.setState()`. ### `.componentWillUnmount()` -TODO +`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in `componentDidMount`. ### `.componentWillUpdate(nextProps, nextState)` -TODO +`componentWillUpdate()` is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render. + +Note that you cannot call `this.setState()` here. If you need to update state in response to a prop change, use `componentWillReceiveProps()` instead. + +> Note +> +> `componentWillUpdate()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. + ### `.defaultProps` @@ -88,7 +163,13 @@ The `displayName` string is used in debugging messages. JSX sets this value auto ### `.forceUpdate(callback)` -TODO +`forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`. + +By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`. + +Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes. + +Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your component "pure" and your application much simpler and more efficient. ### `.props` @@ -122,6 +203,10 @@ You can also return `null` or `false` to indicate that you don't want anything r The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about. +> Note +> +> `render()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. + ### `.setState(nextState, callback)` ```javascript @@ -155,11 +240,19 @@ The second parameter is an optional callback function that will be executed once There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains. -`setState()` will always trigger a re-render unless conditional rendering logic is implemented in `shouldComponentUpdate()`. If mutable objects are being used and the logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders. +`setState()` will always trigger a re-render unless `shouldComponentUpdate()` returns `false`. If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders. ### `.shouldComponentUpdate(nextProps, nextState)` -TODO +Use `shouldComponentUpdate()` to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. + +`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when `forceUpdate()` is used. + +Returning `false` does not prevent child components from re-rendering when *their* state changes. + +Currently, if `shouldComponentUpdate()` returns `false`, then `componentWillUpdate()`, `render()`, and `componentDidUpdate()` will not be invoked. Note that in the future React may treat `shouldComponentUpdate()` as a hint rather than a strict directive, and returning `false` may still result in a re-rendering of the component. + +If you determine a specific component is slow after profiling, you may change it to inherit from `React.PureComponent` which implements `shouldComponentUpdate()` with a shallow prop and state comparison. If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped. ### `.state` From 4713a34c68e1311360de3a33e336ce5367520f2b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Mon, 10 Oct 2016 11:45:54 -0700 Subject: [PATCH 3/4] Dan's feedback. --- docs/docs/reference-react-component.md | 138 ++++++++++++++----------- 1 file changed, 79 insertions(+), 59 deletions(-) diff --git a/docs/docs/reference-react-component.md b/docs/docs/reference-react-component.md index b691684256183..e3e099a6cc42a 100644 --- a/docs/docs/reference-react-component.md +++ b/docs/docs/reference-react-component.md @@ -11,9 +11,9 @@ permalink: docs/react-component.html ## Overview -`React.Component` is an abstract base class, so it rarely makes sense to refer to `React.Component` directly. Instead, you will typically subclass it, and define at least a [`.render()`](#.render) method. +`React.Component` is an abstract base class, so it rarely makes sense to refer to `React.Component` directly. Instead, you will typically subclass it, and define at least a [`render()`](#render) method. -Normally you would define a React component as a plain JavaScript class: +Normally you would define a React component as a plain [JavaScript class](https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Classes): ```javascript class Greeting extends React.Component { @@ -47,46 +47,48 @@ React provides lifecycle methods that you can specify to hook into this process. #### Mounting -React will call [`.componentWillMount()`](#.componentwillmount) and [`.componentDidMount()`](#.componentdidmount) when a component is being inserted into the DOM. +React will call [`componentWillMount()`](#componentwillmount) and [`componentDidMount()`](#componentdidmount) when a component is being inserted into the DOM. #### Updating -State changes can lead to the component being re-rendered. The following methods will be called and are used to determine if the DOM should be updated. +Changes to props or state can lead to the component being re-rendered. A re-rendering is not to be misinterpreted as an [expensive DOM change](/react/docs/rendering-elements.html#react-only-updates-whats-necessary). - - [`.componentWillReceiveProps()`](#.componentwillreceivepropsnextprops) is invoked before a mounted component receives new props and can be used to update state in response to prop changes. - - Components will always re-render when the state is updated. Take a look at [`.shouldComponentUpdate(nextProps, nextState)`](#.shouldcomponentupdatenextprops-nextstate) if you need to change the default behavior. - - [`.componentWillUpdate(nextProps, nextState)`](#.componentwillupdatenextprops-nextstate) can be used for preparation before an update occurs. - - [`.componentDidUpdate(prevProps, prevState)`](#.componentdidupdateprevprops-prevstate) is invoked after an update and can be used to operate on the DOM after the component has been updated. + - [`componentWillReceiveProps()`](#componentwillreceivepropsnextprops) is invoked before a mounted component receives new props and can be used to update state in response to prop changes. + - The default behavior is for a component to re-render when its state changes. Take a look at [`shouldComponentUpdate(nextProps, nextState)`](#shouldcomponentupdatenextprops-nextstate) if you need to change the default behavior. + - [`componentWillUpdate(nextProps, nextState)`](#componentwillupdatenextprops-nextstate) can be used for preparation before an update occurs. + - [`componentDidUpdate(prevProps, prevState)`](#componentdidupdateprevprops-prevstate) is invoked after an update and can be used to operate on the DOM after the component has been updated or to fetch new data in response to prop changes. #### Unmounting -[`.componentWillUnmount()`](#.componentwillunmount) can be used to perform any cleanup, as it is invoked immediately before a component is unmounted and destroyed. +[`componentWillUnmount()`](#componentwillunmount) can be used to perform any cleanup, as it is invoked immediately before a component is unmounted and destroyed. ## Reference - [`constructor(props)`](#constructor) - - [`.componentDidMount()`](#.componentdidmount) - - [`.componentDidUpdate(prevProps, prevState)`](#.componentdidupdateprevprops-prevstate) - - [`.componentWillMount()`](#.componentwillmount) - - [`.componentWillReceiveProps(nextProps)`](#.componentwillreceivepropsnextprops) - - [`.componentWillUnmount()`](#.componentwillunmount) - - [`.componentWillUpdate(nextProps, nextState)`](#.componentwillupdatenextprops-nextstate) - - [`.defaultProps`](#.defaultprops) - - [`.displayName`](#.displayName) - - [`.forceUpdate(callback)`](#.forceupdatecallback) - - [`.props`](#.props) - - [`.propTypes`](#.proptypes) - - [`.render()`](#.render) - - [`.setState(nextState, callback)`](#.setstatenextstate-callback) - - [`.shouldComponentUpdate(nextProps, nextState)`](#.shouldcomponentupdatenextprops-nextstate) - - [`.state`](#.state) + - [`componentDidMount()`](#componentdidmount) + - [`componentDidUpdate(prevProps, prevState)`](#componentdidupdateprevprops-prevstate) + - [`componentWillMount()`](#componentwillmount) + - [`componentWillReceiveProps(nextProps)`](#componentwillreceivepropsnextprops) + - [`componentWillUnmount()`](#componentwillunmount) + - [`componentWillUpdate(nextProps, nextState)`](#componentwillupdatenextprops-nextstate) + - [`defaultProps`](#defaultprops) + - [`displayName`](#displayName) + - [`forceUpdate(callback)`](#forceupdatecallback) + - [`props`](#props) + - [`propTypes`](#proptypes) + - [`render()`](#render) + - [`setState(nextState, callback)`](#setstatenextstate-callback) + - [`shouldComponentUpdate(nextProps, nextState)`](#shouldcomponentupdatenextprops-nextstate) + - [`state`](#state) ### `constructor(props)` The constructor for a React component is called before it is mounted. When implementing the constructor for a `React.Component` subclass, you should call `super(props)` before any other statement. Otherwise, `this.props` will be undefined in the constructor, which can lead to bugs. -The constructor is the right place to initialize state. It's okay to initialize state based on props. Here's an example of a valid `React.Component` subclass constructor: +The constructor is the right place to initialize state. + +It's okay to initialize state based on props if you know what you're doing. Here's an example of a valid `React.Component` subclass constructor: ```js constructor(props) { @@ -97,40 +99,44 @@ constructor(props) { } ``` -### `.componentDidMount()` +Beware of this pattern, as it effectively "forks" the props and can lead to bugs. Instead of syncing props to state, you often want to [lift the state up](/react/docs/lifting-state-up.html). + +If you "fork" props by using them for state, you might also want to implement [`componentWillReceiveProps(nextProps)`](#componentwillreceivepropsnextprops) to keep the state up-to-date with them. But lifting state up is often easier and less bug-prone. + +### `componentDidMount()` `componentDidMount()` is invoked immediately after a component is mounted. Initialization that requires DOM nodes should go here. If you need to load data from a remote endpoint, this is a good place to instantiate the network request. Setting state in this method will trigger a re-rendering. -### `.componentDidUpdate(prevProps, prevState)` +### `componentDidUpdate(prevProps, prevState)` `componentDidUpdate()` is invoked immediately after updating occurs. This method is not called for the initial render. -Use this as an opportunity to operate on the DOM when the component has been updated. +Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed). > Note > -> `componentDidUpdate()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. +> `componentDidUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdatenextprops-nextstate) returns false. -### `.componentWillMount()` +### `componentWillMount()` `componentWillMount()` is invoked immediately before mounting occurs. It is called before `render()`, therefore setting state in this method will not trigger a re-rendering. Avoid introducing any side-effects or subscriptions in this method. -This is the only lifecycle hook called on server rendering. +This is the only lifecycle hook called on server rendering. Generally, we recommend using the `constructor()` instead. -### `.componentWillReceiveProps(nextProps)` +### `componentWillReceiveProps(nextProps)` `componentWillReceiveProps()` is invoked before a mounted component receives new props. If you need to update the state in response to prop changes (for example, to reset it), you may compare `this.props` and `nextProps` and perform state transitions using `this.setState()` in this method. Note that React may call this method even if the props have not changed, so make sure to compare the current and next values if you only want to handle changes. This may occur when the parent component causes your component to re-render. -`componentWillReceiveProps()` is not invoked if you just call `this.setState()`. +`componentWillReceiveProps()` is not invoked if you just call `this.setState()` -### `.componentWillUnmount()` +### `componentWillUnmount()` -`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in `componentDidMount`. +`componentWillUnmount()` is invoked immediately before a component is unmounted and destroyed. Perform any necessary cleanup in this method, such as invalidating timers, canceling network requests, or cleaning up any DOM elements that were created in `componentDidMount` -### `.componentWillUpdate(nextProps, nextState)` +### `componentWillUpdate(nextProps, nextState)` `componentWillUpdate()` is invoked immediately before rendering when new props or state are being received. Use this as an opportunity to perform preparation before an update occurs. This method is not called for the initial render. @@ -138,12 +144,12 @@ Note that you cannot call `this.setState()` here. If you need to update state in > Note > -> `componentWillUpdate()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. +> `componentWillUpdate()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdatenextprops-nextstate) returns false. -### `.defaultProps` +### `defaultProps` -`defaultProps` can be defined as a property on the component class itself, to set the default props for the class. For example: +`defaultProps` can be defined as a property on the component class itself, to set the default props for the class. This is used for undefined props, but not for null props. For example: ```js class CustomButton extends React.Component { @@ -155,31 +161,45 @@ CustomButton.defaultProps = { }; ``` -If `props.color` is not provided, it will be set by default to `'blue'`. +If `props.color` is not provided, it will be set by default to `'blue'`: + +```js + render() { + return ; // props.color will be set to blue + } +``` + +If `props.color` is set to null, it will remain null: + +```js + render() { + return ; // props.color will remain null + } +``` -### `.displayName` +### `displayName` The `displayName` string is used in debugging messages. JSX sets this value automatically; see [JSX in Depth](/react/docs/jsx-in-depth.html). -### `.forceUpdate(callback)` +### `forceUpdate(callback)` -`forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()`. +`forceUpdate()` can be invoked on any mounted component when you know that some deeper aspect of the component's state has changed without using `this.setState()` -By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()`. +By default, when your component's state or props change, your component will re-render. However, if these change implicitly (eg: data deep within an object changes without changing the object itself) or if your `render()` method depends on some other data, you can tell React that the component needs re-rendering by calling `forceUpdate()` -Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()`. This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes. +Calling `forceUpdate()` will cause `render()` to be called on the component, skipping `shouldComponentUpdate()` This will trigger the normal lifecycle methods for child components, including the `shouldComponentUpdate()` method of each child. React will still only update the DOM if the markup changes. -Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()`. This makes your component "pure" and your application much simpler and more efficient. +Normally you should try to avoid all uses of `forceUpdate()` and only read from `this.props` and `this.state` in `render()` This makes your component "pure" and your application much simpler and more efficient. -### `.props` +### `props` `this.props` contains the props that were defined by the caller of this component. See [Components and Props](/react/docs/components-and-props.html) for an introduction to props. In particular, `this.props.children` is a special prop, typically defined by the child tags in the JSX expression rather than in the tag itself. -### `.propTypes` +### `propTypes` -`propTypes` can be defined as a property on the component class itself, to define what types the props should be. It should be a map from prop names to types as defined in `React.PropTypes`. In development mode, when an invalid value is provided for a prop, a warning will be shown in the JavaScript console. In production mode, `propTypes` checks are skipped for efficiency. +`propTypes` can be defined as a property on the component class itself, to define what types the props should be. It should be a map from prop names to types as defined in `React.PropTypes` In development mode, when an invalid value is provided for a prop, a warning will be shown in the JavaScript console. In production mode, `propTypes` checks are skipped for efficiency. For example, this code ensures that the `color` prop is a string: @@ -193,21 +213,21 @@ CustomButton.propTypes = { }; ``` -### `.render()` +### `render()` The `render()` method is required. When called, it should examine `this.props` and `this.state` and return a single React element. This element can be either a representation of a native DOM component, such as `
`, or another composite component that you've defined yourself. -You can also return `null` or `false` to indicate that you don't want anything rendered. React will just render a comment tag. When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null`. +You can also return `null` or `false` to indicate that you don't want anything rendered. React will just render a comment tag. When returning `null` or `false`, `ReactDOM.findDOMNode(this)` will return `null` The `render()` function should be pure, meaning that it does not modify component state, it returns the same result each time it's invoked, and it does not directly interact with the browser. If you need to interact with the browser, perform your work in `componentDidMount()` or the other lifecycle methods instead. Keeping `render()` pure makes components easier to think about. > Note > -> `render()` will not be invoked if [`.shouldComponentUpdate()`](#.shouldcomponentupdatenextprops-nextstate) returns false. +> `render()` will not be invoked if [`shouldComponentUpdate()`](#shouldcomponentupdatenextprops-nextstate) returns false. -### `.setState(nextState, callback)` +### `setState(nextState, callback)` ```javascript void setState( @@ -226,7 +246,7 @@ Here is the simple object usage: this.setState({mykey: 'my new value'}); ``` -It's also possible to pass a function with the signature `function(state, props) => newState`. This can be useful in some cases when you want to enqueue an atomic update that consults the previous value of state and props before setting any values. For instance, suppose we wanted to increment a value in state: +It's also possible to pass a function with the signature `function(state, props) => newState` This can be useful in some cases when you want to enqueue an atomic update that consults the previous value of state and props before setting any values. For instance, suppose we wanted to increment a value in state: ```javascript this.setState((prevState, currentProps) => { @@ -234,19 +254,19 @@ this.setState((prevState, currentProps) => { }); ``` -The second parameter is an optional callback function that will be executed once `setState` is completed and the component is re-rendered. +The second parameter is an optional callback function that will be executed once `setState` is completed and the component is re-rendered. Generally we recommend using `componentDidUpdate()` for such logic instead. `setState()` does not immediately mutate `this.state` but creates a pending state transition. Accessing `this.state` after calling this method can potentially return the existing value. There is no guarantee of synchronous operation of calls to `setState` and calls may be batched for performance gains. -`setState()` will always trigger a re-render unless `shouldComponentUpdate()` returns `false`. If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders. +`setState()` will always trigger a re-render unless `shouldComponentUpdate()` returns `false` If mutable objects are being used and conditional rendering logic cannot be implemented in `shouldComponentUpdate()`, calling `setState()` only when the new state differs from the previous state will avoid unnecessary re-renders. -### `.shouldComponentUpdate(nextProps, nextState)` +### `shouldComponentUpdate(nextProps, nextState)` Use `shouldComponentUpdate()` to let React know if a component's output is not affected by the current change in state or props. The default behavior is to re-render on every state change, and in the vast majority of cases you should rely on the default behavior. -`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true`. This method is not called for the initial render or when `forceUpdate()` is used. +`shouldComponentUpdate()` is invoked before rendering when new props or state are being received. Defaults to `true` This method is not called for the initial render or when `forceUpdate()` is used. Returning `false` does not prevent child components from re-rendering when *their* state changes. @@ -254,7 +274,7 @@ Currently, if `shouldComponentUpdate()` returns `false`, then `componentWillUpda If you determine a specific component is slow after profiling, you may change it to inherit from `React.PureComponent` which implements `shouldComponentUpdate()` with a shallow prop and state comparison. If you are confident you want to write it by hand, you may compare `this.props` with `nextProps` and `this.state` with `nextState` and return `false` to tell React the update can be skipped. -### `.state` +### `state` The state contains data specific to this component that may change over time. The state should be a plain JavaScript object, with the keys defined according to the `React.Component` subclass. There are no special state keys with behavior defined by the core `React.Component` class itself. From 4f2c21e6ce489fc4bb3cf26c29e9c4a40b9d48f7 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?H=C3=A9ctor=20Ramos?= Date: Mon, 10 Oct 2016 11:48:03 -0700 Subject: [PATCH 4/4] Minor formatting nit. --- docs/docs-old/05-reusable-components.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/docs-old/05-reusable-components.md b/docs/docs-old/05-reusable-components.md index 4bf562dec6620..7ef62638bdd6a 100644 --- a/docs/docs-old/05-reusable-components.md +++ b/docs/docs-old/05-reusable-components.md @@ -255,7 +255,7 @@ class Greeting extends React.Component { } ``` -If you don't use ES6 yet, you may use the React.createClass helper instead: +If you don't use ES6 yet, you may use the `React.createClass` helper instead: ```javascript