Basically, I've got this pretty simple react component. What it does is, is wrap around 'react-intercom' and only render it if there is a change in the state. To simplify the question, I've hardwired the shouldCompoenentUpdate()
method to always return false.
import React from 'react';
import Intercom from 'react-intercom';
class IntercomWrapper extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
// console.log(!!nextProps.user && nextProps.user.userId !== this.props.user.userId);
// return !!nextProps.user && nextProps.user.userId !== this.props.user.userId;
return false;
}
render() {
console.log('rendering');
return <Intercom {...this.props} />;
}
};
export default IntercomWrapper;
What happens is that it always rerenders, which should not happen.
Anyone has any idea why would that happen?
1. Memoization using useMemo() and UseCallback() Hooks. Memoization enables your code to re-render components only if there's a change in the props. With this technique, developers can avoid unnecessary renderings and reduce the computational load in applications.
Currently, if shouldComponentUpdate() returns false , then UNSAFE_componentWillUpdate() , render() , and componentDidUpdate() will not be invoked. In the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.
Preventing Re-Renders: The Old Way To prevent the render method from being called, set the return to false, which cancels the render. This method gets called before the component gets rendered. Sometimes you may want to prevent re-render even if a component's state or prop has changed.
Explanation: Just notice, that <Rendering /> is called twice but only 1 time component is rendered on the screen. Example 2: In this example, we will display call the component by passing Integers as props. But only even numbers will be displayed. Odd numbers will be prevented from rendering by returning null.
I figured it out eventually: The problem was that the wrapping component was receiving state changes, and was rerendering all children unconditionally (which is normal behaviour. It was a matter of rearranging components (getting this Intercom wrapper out of my <Layout>
component). Thanks all for the help! Cheers!
This wont prevent rendering of child components:
From the DOCS:
Returning false does not prevent child components from re-rendering when their state changes. ...
Note that in the future React may treat shouldComponentUpdate() as a hint rather than a strict directive, and returning false may still result in a re-rendering of the component.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With