Vivek  Ghanchi
Vivek Ghanchi

Reputation: 232

Which Life cycle method should be preferred when using redux?

Which life cycles method should be preferred while getting data from redux store in props?

Upvotes: 0

Views: 1169

Answers (2)

Kaushal Madani
Kaushal Madani

Reputation: 78

Generally you will not need any life cycle method but it depends on your usecase and how you want to use your data that is coming from redux store.Generally flow can be like this:

  1. Connect your component with redux store.
  2. Map your state to props and get the that you want in component.
  3. In componentDidMount(),you will get the data in props.
  4. And if you want to check if your data is changed or not from store then you can use componentDidUpdate(prevProps,prevState) method to check.

Here is a little demo:

class YourComponent extends React.Component {


  componentDidMount() {
    console.log("You will get your data here:",this.props.data);
  }

  componentDidUpdate(prevProps, prevState,) {
    //Here you can compare data if it is changed or not.
    if(prevProps.data !== this.props.data){
        console.log("Your data is changed.");   
    }
  }

}

//Map your state to props
const mapStateToProps = store =>{
    const data = store.data
    return {
        data
    }
};

//Connect your component with redux store.
export default connect(mapStoreToProps)(YourComponent);

Upvotes: 1

wentjun
wentjun

Reputation: 42556

I am not sure how exactly is your component written, but the general pattern to follow would be to connect your component to your redux store, and map the value from your store to your components props.

From there, your component will be subscribed to the data from your store, which you can access on componentDidMount lifecycle hook, and any other updates to the store can be accessed in the componentDidUpdate hook. Similarly, any changes on your props will trigger re-rendering on your component.

const mapStateToProps = (state) => ({
  data: state.data,
});

class Checkbox extends React.Component {

  componentDidMount() {
    const { data } = this.props;
  }

  componentDidUpdate(prevProps, prevState,) {

  }

}

export default connect(mapStateToProps)(Checkbox);

Upvotes: 1

Related Questions