Reputation: 232
Which life cycles method should be preferred while getting data from redux store in props?
Upvotes: 0
Views: 1169
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:
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
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