Recently, I've started working with the React JS library and thought to make some useful notes and share them as I go
through some of basic react concepts and in order
to understand it better. I decided to understand the life cycles of a React app and component.
The life cycle of a Web page or app or a component really means how a page is loaded, rendered, and when and how various events are fired to do certain things. These are useful when you plan to write code to load data before a page is acually rendered in a browser.
Let's run this simple React component code.
- import React from 'react';
- class ReactComponentLifeCycle extends React.Component {
- constructor(props) {
- console.log('constructor called') //This right place to set the state as it executes only once
- super(props);
- this.state = {
- data: 'Rajendra',
- }
- this.updateState = this.updateState.bind(this);
- };
- updateState(e) {
- this.setState({data: e.target.value});
- }
- componentWillMount() {
- console.log('componentWillMount called') //Sometimes based some conditional we need to changes the state
- }
- componentDidMount() {
- console.log('componentDidMount called') // Here you can call the external servies Ajax/Rest API's
- }
- componentWillReceiveProps() {
- console.log('componentWillReceiveProps called') // Here you can read Next and Previous Props/states
- }
- shouldComponentUpdate() {
- return true; // controls conditional rendering
- }
- componentWillUpdate() {
- console.log('componentWillUpdate called'); //on changes of state or props
- }
- componentDidUpdate() {
- console.log('componentDidUpdate called') //on changes of state or props
- }
- componentWillUnmount() {
- console.log('componentWillUnmount called') //Clean up or unsubscribe your observables
- }
- render() {
- console.log('render called') //It calls every time when state or prop changes
- return (
- <div>
- <h3>{this.props.myNumber}</h3>
- <input type = "text" value = {this.state.data}
- onChange = {this.updateState} />
- </div>
- );
- }
- }
- export default ReactComponentLifeCycle;



Join the conversation! Your thoughts help the community grow.