Reputation: 1052
We all know that constructor -> componentWillMount -> componentDidMount
is order of execution.
Now when redux comes into play and trying to access redux properties in our component life cycle. What is the order in which connect will execute so that data is available lifecycle methods ignoring and data updation to redux. The possibilities are
1. Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount
2. constructor -> Connect (DATA AVAILABLE) -> componentWillMount & componentDidMount
3. constructor -> componentWillMount -> Connect (DATA AVAILABLE) -> componentDidMount
4. constructor -> componentWillMount -> componentDidMount -> Connect (DATA AVAILABLE)
and is the order consistent or depends on the data that is loaded?
and is it different between react and react native
and is it okay to defined redux properties as required in PropType
Upvotes: 13
Views: 5497
Reputation: 281726
connect
is an HOC which wraps your component, so the component lifecycle method comes after the connect lifecycle. For simple understanding, you can think of connect being written like this
const connect = (mapStateToProps, mapDispatchToProps) => (Component) => {
return class ReduxApp extends React.Component {
// lifecycle of connect
render() {
return (
<Component {...mapStateToProps(state)} />
)
}
}
}
Now whenever your state updates, connect will shallow compare the list of props to be returned to Component and if there is a change update the props, after which the component lifecycle method runs like a prop is being updated.
In short the execution initially is
Connect (DATA AVAILABLE) -> constructor & componentWillMount & componentDidMount
Once the data is updated
Connect (DATA AVAILABLE) -> componentWillReceiveProps/getDerivedStateFromProps -> componentWillUpdate -> render -> componentDidUpdate
Upvotes: 12
Reputation: 215
The initial execution order would be -
Connect (DATA AVAILABLE) -> constructor & componentWillMount & Render & componentDidMount
When the site is fired up, redux connect would be initialized first with its default states and actions before the component mount life cycles. However, if there are API calls in redux, the component mount life cycles will not wait for the data. Instead component update life cycles will be invoked, if the component is already mounted and redux returns a data.
Upvotes: 4