0
votes

I have this React.memo component that I want to render only if the props doesn't change with sending a second argument isEqual function. When I console.log the wrapper component and the memmoized component I can see that its being rendered with the same props.. What am I doing wrong?

My wrapper component

export const WrapperComponent= props => {
    console.log('MemoizeComponent', props);
    return (
       <MemoizeComponent name="memo"/>
    );
}

export const WrapperComponent;

My memmoized component

export const Component = props => {
    console.log('component: ', props.name)
    return (
       <div>{props.name}</div>
    );
}

function isEqual(prevProps, nextProps) {
    console.log(prevProps.name);
    console.log(nextProps.name);
    return prevProps.name === nextProps.name;
};

export const MemoizeComponent = React.memo(Component, isEqual);

console output:

memo
memo
component:memo
memo
memo
component:memo
1
I want to render only if the props doesn't change with sending a second argument isEqual function that sounds like an opposite to what React.memo does - prevent re-render if props didn't change. - Clarity

1 Answers

0
votes

Not sure what your question is but your code as is works correctly:

const { useState, memo, useRef } = React;
const useRendered = () => {
  const rendered = useRef(0);
  rendered.current++;
  return rendered.current;
};
function App() {
  const [, setRender] = useState();
  const rendered = useRendered();
  return (
    <div>
      <div>rendered {rendered} times</div>
      <button onClick={() => setRender({})}>
        re render
      </button>
      <WrapperComponent name="memo" />
    </div>
  );
}

const WrapperComponent = props => {
  return <MemoizeComponent name="memo" />;
};
const Component = props => {
  const rendered = useRendered();
  return (
    <div>
      {props.name} rendered {rendered} times
    </div>
  );
};

function isEqual(prevProps, nextProps) {
  return prevProps.name === nextProps.name;
}

const MemoizeComponent = memo(Component, isEqual);

ReactDOM.render(<App />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="root"></div>