ReactJS Component state and life cycle
Component state
ReactJS Component state is the plain JavaScript object containing
the data that can be used to render on the screen. The state is managed inside the component, but
the RecatJS component props are passed into the container from the outside. So, the state object
is internal to a component and contains the data that is supposed to be changed
over time.
The component starts with default state when it is mounted,
but the state may change (the state object is mutable) due to user events over
time.
It is not mandatory for a component to have a state. The state adds
complexity and reduces predictability. A component without a state is more desirable,
but in an interactive app, this cannot be done. It is good practice to avoid
having too many stateful components.
Lifecycle Methods
The render() method is the only method needed for creating a component, but many lifecycle methods and specs are also available those are extremely helpful when we want our component to do anything significant.
You can refer to the lifecycle method diagram for the sequence of execution/
- componentWillMount is invoked before rendering, on both the server and the client-side.
- componentDidMount is executed only once, on the client-side, after rendering occurs. We can use it to update the state so we can trigger the other lifecycle methods.
- componentWillReceiveProps is called as soon as the props are modified before another render has occurred. It is triggered by the setNewNumber when the state is updated.
- componentWillUpdate is invoked just before rendering.
- shouldComponentUpdate method returns true or false value. This method determines if the component should be updated or not. This is set to true by default.
- componentDidUpdate is invoked just after rendering.
- componentWillUnmount is invoked prior to the component is unmounted .
Other APIs
- The setState( ) method is used to update the state object properties. This object should not be updated using the assignment operator.
- The forceUpdate( ) method is used to update the UI.
- The defaultProps class property can be used to set the default properties of the component.
- The displayName class property is used for debugging messages.
Example
<div id='root'></div>
.myPanel { background-color:#000077; color:white; height:70vh; width:90vh; text-align:center; } h2 { color:red; } p { color:orange; }
class Myclock extends React.Component { constructor(props) { super(props); this.start=new Date().getTime(); this.state = { t:new Date() } } componentDidMount() { this.tid=setInterval(()=>this.setState({t:new Date()}),1000); } componentWillUnmount() { clearInterval(this.tid); } render() { return <div class="myPanel"><h1>Timer</h1><hr/> <h2>{parseInt((this.state.t.getTime()-this.start)/1000)} <p>Seconds </p> </h2><hr/> </div>; } } ReactDOM.render(<Myclock/>, document.getElementById('root'));