How can I prevent my functional component from re-

2020-05-26 09:19发布

问题:

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:

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);


回答2:

React.memo is same thing as React.PureComponent

You can use it when you don't want to update a component that you think is static so, Same thing as PureCompoment.

For class Components:

class MyComponents extends React.PureCompoment {}

For function Components:

const Mycomponents = React.memo(props => {
  return <div> No updates on this component when rendering </div>;
});

So it's just creating a component with React.memo

To verify that your component doesn't render you can just activate HightlightUpdates in react extension and check your components reaction on rendering



回答3:

We can use memo for prevent render in function components for optimization goal only. According React document:

This method only exists as a performance optimization. Do not rely on it to “prevent” a render, as this can lead to bugs.