Reputation: 21
Parent component receive props data(exists in redux and are different every second) which cause re-renders.How to avoid unnecessary re-renders of Child component? React.memo does not work because callback is different every time
class Parent extends React.Component {
constructor(props) {
super(props);
this.state = {
value: '',
};
}
shouldComponentUpdate(nextProps, nextState) {
return (!isEqual(nextProps.data, this.props.data)
|| !isEqual(nextState, this.state));
}
onChangeHnadler = (e) => {
this.setState({value: e.target.value})
}
render () {
const { value } = this.state;
return (
<Child value={value} onChange={this.onChangeHnadler}/>
);
}
const Child = React.memo(({value, onChange}) => {
return <input value={value} onChange={onChange}/>
});
Upvotes: 0
Views: 175
Reputation: 202836
Use the memo
compare function, the second parameter passed to memo
HOC. I'm assuming the value
prop is more stable? You can hint to react to try and skip rerenders if
const areEqual = (prevProps, nextProps) => {
return prevProps.value === nextProps.value;
};
const Child = React.memo(
({value, onChange}) => <input value={value} onChange={onChange}/>,
areEqual
);
Note
This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.
Upvotes: 1