If you defined below methods to a component, their will be call in order (you may forget if you don't need):
constructor(props)
componentWillMount()
componentWillReceiveProps(nextProps)
shouldComponentUpdate(nextProps, nextState)
componentWillUpdate()
render()
componentDidUpdate()
componentDidMount()
componentWillUnmount()
- If you want to define the above methods, you have to use
class
to define a component. - Not all of them will be called everytime.
- See React doc for more details or maybe keep reading below.
render()
(always) which returns JSXconstructor(props)
to define initial state of the componentcomponentDidMount()
to call fetch data API for your component
class App extends React.Component{
constructor(props){
super(props)
this.state = {
userName: ''
}
}
componentDidMount(){
fetch('http://my.api.com/account').then((data) => {
this.setState({
userName: data.userName
})
})
}
render(){
return <div>
User name: {this.state.userName}
</div>
}
}
- First the component will be initiated (
constructor()
runs). - Then it will be rendered (
render()
runs) then added to the DOM. - After added to the DOM,
componentDidMount()
will run only once. - Everytime component receives new
props
orstate
change, the component will be re-rendered (render()
runs again) then it will be updated (if nessessary) to the DOM.