Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order of component life cycle with react-redux connect and redux data

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

like image 735
Gaudam Thiyagarajan Avatar asked Jun 07 '18 07:06

Gaudam Thiyagarajan


People also ask

What is the order of phases of component lifecycle in React?

Each component in React has a lifecycle which you can monitor and manipulate during its three main phases. The three phases are: Mounting, Updating, and Unmounting.

What is the lifecycle methods order in mounting React component?

React supports three mounting lifecycle methods for component classes: componentWillMount() , render() , and componentDidMount() . componentWillMount() will be called first followed by the render() method and finally the componentDidMount() method.

What is the life cycle of Redux?

When we want to implement Redux in the React, we also need three things: save store state in React. get the state in React component. dispatch action in React component.


1 Answers

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
like image 151
Shubham Khatri Avatar answered Sep 29 '22 22:09

Shubham Khatri