Thinking In React: Component Lifecycle Methods
React is a flexible framework that makes it easy to build single-page web applications. One of its tools is a set of lifecycle methods which you can add to your components. These methods are called at different stages in the life of a component, and they make it possible to manage your component's changing state and resources.
In this course, you'll take a look at each of React's seven lifecycle methods and see how they can work together to create dynamic React components.
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/babel-core/5.8.24/browser.js"></script>
<script src="https://npmcdn.com/react@latest/dist/react-with-addons.js"></script>
<script src="https://npmcdn.com/react-dom@latest/dist/react-dom.js"></script>
<script src="https://facebook.github.io/react/js/jsfiddle-integration-babel.js"></script>
<div id="container">
<!-- This element's contents will be replaced with your component. -->
</div>
JavaScript 1.7
// componentWillMount
// componentDidMount
// componentWillReceiveProps(nextProps)
// shouldComponentUpdate(nextProps, nextState)
// componentWillUpdate(nextProps, nextState)
// componentDidUpdate(prevProps, prevState)
// componentWillUnmount
var MinuteCounter = React.createClass({
componentWillMount() {
var minutes = Math.floor(this.props.seconds / 60);
var seconds = this.props.seconds % 60;
this.setState({ minutes, seconds });
},
componentWillReceiveProps(nextProps) {
var minutes = Math.floor(nextProps.seconds / 60);
var seconds = nextProps.seconds % 60;
this.setState({ minutes, seconds });
},
shouldComponentUpdate(nextProps, nextState) {
return nextProps.seconds % 5 === 0;
},
componentWillUpdate(nextProps, nextState) {
if (nextState.seconds === 0) this.props.onNewMinute(nextState.minutes);
},
render() {
return <h1>
{this.state.minutes} min {this.state.seconds} sec
</h1>;
}
});
var Timer = React.createClass({
getInitialState() {
return { seconds: 0 };
},
componentDidMount() {
this.intervalId = setInterval(() => {
this.setState({ seconds: this.state.seconds + 1 });
}, 100);
},
componentWillUnmount() {
clearInterval(this.intervalId);
},
render() {
return <MinuteCounter
seconds={this.state.seconds}
onNewMinute={(min) => console.log('starting minute', min)}
/>
}
});
var Toggle = React.createClass({
getInitialState() {
return { on: false }
},
toggle() {
this.setState({ on: !this.state.on });
},
render() {
return <div>
<button onClick={this.toggle}> Toggle </button>
{this.state.on ? <Timer />: 'OFF'}
</div>
}
});
ReactDOM.render(
<Toggle />,
document.getElementById('container')
);