From 3c8b63ea6c4c235fe34a6475efe3f9496cde7006 Mon Sep 17 00:00:00 2001 From: Dan Abramov Date: Fri, 18 Nov 2016 18:24:27 +0000 Subject: [PATCH] Merge pull request #8346 from shubheksha/docs/improve-state-and-lifecycle Improved sections of state and lifecycle docs --- docs/docs/state-and-lifecycle.md | 14 ++++++++++++++ 1 file changed, 14 insertions(+) diff --git a/docs/docs/state-and-lifecycle.md b/docs/docs/state-and-lifecycle.md index ab585aff03..5aa95e937f 100644 --- a/docs/docs/state-and-lifecycle.md +++ b/docs/docs/state-and-lifecycle.md @@ -309,6 +309,18 @@ ReactDOM.render( Now the clock ticks every second. +Let's quickly recap what's going on and the order in which the methods are called: + +1) When `` is passed to `ReactDOM.render()`, React calls the constructor of the `Clock` component. Since `Clock` needs to display the current time, it initializes `this.state` with an object including the current time. We will later update this state. + +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 `tick()` 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 `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. + ## Using State Correctly There are three things you should know about `setState()`. @@ -329,6 +341,8 @@ Instead, use `setState()`: this.setState({comment: 'Hello'}); ``` +The only place where you can assign `this.state` is the constructor. + ### State Updates May Be Asynchronous React may batch multiple `setState()` calls into a single update for performance.