When hiddenLogo
changes value, the component is re-rendered. I want this component to never re-render, even if its props change. With a class component I could do this by implementing sCU like so:
shouldComponentUpdate() { return false; }
But is there a way to do with with React hooks/React memo?
Here's what my component looks like:
import React, { useEffect } from 'react'; import PropTypes from 'prop-types'; import ConnectedSpringLogo from '../../containers/ConnectedSpringLogo'; import { Wrapper, InnerWrapper } from './styles'; import TitleBar from '../../components/TitleBar'; const propTypes = { showLogo: PropTypes.func.isRequired, hideLogo: PropTypes.func.isRequired, hiddenLogo: PropTypes.bool.isRequired }; const Splash = ({ showLogo, hideLogo, hiddenLogo }) => { useEffect(() => { if (hiddenLogo) { console.log('Logo has been hidden'); } else { showLogo(); setTimeout(() => { hideLogo(); }, 5000); } }, [hiddenLogo]); return ( <Wrapper> <TitleBar /> <InnerWrapper> <ConnectedSpringLogo size="100" /> </InnerWrapper> </Wrapper> ); }; Splash.propTypes = propTypes; export default Splash;
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.
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.
useMemo will only recompute the memoized value when one of the dependencies has changed. This optimization helps to avoid expensive calculations on every render. Since we supply an empty list of dependencies, useMemo will not recalculate the value when Parent re-renders.
As we already saw before, React re-renders a component when you call the setState function to change the state (or the provided function from the useState hook in function components).
As G.aziz said, React.memo functions similarly to pure component. However, you can also adjust its behavior by passing it a function which defines what counts as equal. Basically, this function is shouldComponentUpdate, except you return true if you want it to not render.
const areEqual = (prevProps, nextProps) => true; const MyComponent = React.memo(props => { return /*whatever jsx you like */ }, areEqual);
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