This is a reference guide to help developers quickly figure out which lifecycle method will best fit a solution they're currently working on in React.
constructor(props)
The constructor for a React component is the first method that gets called. This is where you should initiate state. You should ensure you execute super(props)
first. Otherwise, bugs will crop up.
constructor(props) {
super(props);
this.state = {
count: props.initialCount
};
}
componentWillMount()
This method is called just before component mounting and render method. Setting state here won't trigger a re-render. This method sounds like a nice place to set the component's initial state. However, React's official guidelines recommend using the constructor()
instead.
componentWillMount() {
// perform setState operations
}
render()
This is a mandatory method for all React components. It will be invoked when state changes, when the parent component causes it to re-render, or when component.forceUpdate()
is called.
The render()
method is where you put your JSX code. You can also return false
or null
if you don't want to render anything. You can read values from this.prop
and this.state
, but you can't call this.setState()
(or call another function that does). You should also not directly interact with the DOM. Instead, use componentDidMount()
.
render() {
const {message} = this.state;
return(
<div>
h1>List of Messages</h1>
<MessageView message={message} />
</div>
)
}
componentDidMount()
This method is invoked right after the component has been mounted and render()
has been called. Once a component mounts, it means you have access to the actual DOM nodes. This is a good place for performing network requests such as an API call. If you set state here, a re-render will be triggered.
componentDidMount = () => {
this.props.fetchContacts()
}
shouldComponentUpdate(nextProps, nextState)
This method is invoked just before render()
whenever there are new props or state changes. The method should only return true
or false
. If you return false
, this means the render
function won't be called. However, do note that:
- this method isn't called in the initial rendering
- child components will still re-render if you return
false
- future versions may not enforce this directive, but instead use it as a hint.
This method has access to nextProps
and nextState
, which gives you an opportunity to compare them with the current props/state and determine if a re-render is necessary. This is a good place to implement performance optimization code.
shouldComponentUpdate(nextProps, nextState) {
// put performance optimization code here
return true;
}
Continue reading %React Lifecycle Reference Guide%
by Michael Wanyoike via SitePoint
No comments:
Post a Comment