Reputation: 700
I am trying to render my component when props changes only, unfortunately, it keeps rendering even when the props is unchanged, my codes is as follow:
componentDidUpdate(prevProps,prevState){
if(prevProps.data !== this.props.data){
this.props.getData(userID)
}
}
render(){
//console.log('render') infinite rendering even when this.props.data is unchanged
return(
<Mycomponent data={this.props.data}/>
)
}
const mapStateToProps = (state) => ({
data: state.api.data,
})
export default connect(mapStateToProps, mapDispatchToProps)(Component1)
Upvotes: 1
Views: 71
Reputation: 20755
From the docs,
getDerivedStateFromProps
is invoked right before calling the render method, both on the initial mount and on subsequent updates. It should return an object to update the state, or null to update nothing.
You must use this method,
static getDerivedStateFromProps(nextProps, prevState){
if(nextProps.someValue!==prevState.someValue){
//do something
}
else return null;
}
Upvotes: 0
Reputation: 533
I believe using a PureComponent instead of a Component will ensure that the component only renders when it receives new information. This is how I would do it:
import React, { PureComponent } from "react";
import Mycomponent from "./Mycomponent";
export default class WrapperComponent extends PureComponent {
componentDidUpdate(prevProps,prevState){
if(prevProps.data !== this.props.data){
this.props.getData(userID)
}
}
render(){
return(
<Mycomponent data={this.props.data}/>
)
}
}
Upvotes: 1