State
Create Component

//index.html
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Document</title>
</head>
<body>
	<div id = "root"></div>
	<script src="https://fb.me/react-0.14.3.js"></script>
	<script src="https://fb.me/react-dom-0.14.3.js"></script>
	<script src="https://unpkg.com/babel-standalone@6.26.0/babel.min.js"></script>
	<script src="script.js" type = "text/babel"></script>
</body>
</html>
		
function Clock(props) {
  return (
    <div>
      <h1>Hello, world!</h1>
      <h2>It is {props.date.toLocaleTimeString()}.</h2>
    </div>
  );
}

function tick() {
  ReactDOM.render(
    <Clock date={new Date()} />,
    document.getElementById('root')
  );
}

setInterval(tick, 1000);
		
State
  • state is often called local or encapsulated, is not accessible to any component other than the one that owns and sets it
  • Any state is always owned by some specific component, and any data or UI derived from that state can only affect components “below” them in the tree
  • setState() change state and re-render a component
  • When you call setState(), React merges the object you provide into the current state
  • class Clock extends React.Component {
      constructor(props) {
        super(props);
        this.state = {date: new Date()};
      }
    
      //mounting, whenever the Clock is rendered to the DOM for the first time
      componentDidMount() {
    	  this.timerID = setInterval(
          () => this.tick(),
          1000
        );
      }
    
      //unmounting, whenever the DOM produced by the Clock is removed
      componentWillUnmount() {
    	  clearInterval(this.timerID);
      }
    
      tick() {
        this.setState({ //call setState() with an object containing the current time
          date: new Date()
        });
      }
    
      render() {
        return (
          <div>
            <h1>Hello, world!</h1>
            <h2>It is {this.state.date.toLocaleTimeString()}.</h2>
          </div>
        );
      }
    }
    
    function App() {
      return (
        <div>
          <Clock />
          <Clock />
          <Clock />
        </div>
      );
    }
    
    ReactDOM.render(
      <App />,
      document.getElementById("root")
    );
    		
    Single Source of Truth
  • In many React applications, group all state data in the root component
  • State data can be passed down the component tree via properties
  • Data can be passed back up the tree to the root via two-way function binding