React shouldComponentUpdate example with functional components

Hi,

If we would like to use functional components instead of classes in this example, then how we should replace the ‘shouldComponentUpdate()’ method to render in even numbers?

You could accomplish the same thing with React.memo and providing a areStatesEqual callback - it would work the same except the logic would be inverted. You can read about it here.

Thanks Kevin for reply, however I feel I am lost in writing callback, can someone help?

function ComponentShouldUpdateParent () {
  const [counter, setCounter] = useState(0)

  return (
    <div>
      <button onClick={() => setCounter(counter + 1)}>Add</button>
      <EvenCounter counter={counter} />
    </div>
  )
}

const EvenCounter = React.memo(({ counter }) => {
  function checkEven (nextProps, nextState) {
    if (nextProps.counter % 2 === 0) 
  }

  return (
    <div>
      <h2>{counter}</h2>
    </div>
  )

That is a whacky function you have there. I don’t understand they syntax you are going for.

You return false if you want it to update (the opposite of shouldComponentUpdate).

This is a little easier when you are breaking things up into files and using exports because you can break things up. We could simulate that here with something like:

const UnmemozidedEvenCounter = ({ counter }) => {
  return  (
    <div>
      <h2>{counter}</h2>
    </div>
  );
};

const areStatesEqual = (prevProps, newProps) => nextProps.counter % 2 === 0;

const EvenCounter = React.memo(UnmemozidedEvenCounter,  areStatesEqual);

You could put it all together like:

const EvenCounter = React.memo(
   ({ counter }) => {
      return  (
        <div>
           <h2>{counter}</h2>
        </div>
      );
  },
  (prevProps, newProps) => nextProps.counter % 2 === 0,
};

or something like that. I haven’t tried it out, I’m just writing it out.

Hi Kevin, thanks for leads and understand your logic behind but can’t get it worked.

Right, so a working SCU would be:

  shouldComponentUpdate(nextProps, nextState) {
    return !(nextProps.value % 2);
  }

So, for our AE, we need the opposite logic. If we break everything apart, I think it would look something like this:

const OnlyEvensPreMemo = props => <h1>{ props.value }</h1>;
const areEqual = next => next.value % 2 !== 0;
const OnlyEvens = React.memo(OnlyEvensPreMemo, areEqual);

or we could put it all together:

const OnlyEvens = React.memo(
  props => <h1>{ props.value }</h1>,
  next => next.value % 2 !== 0,
);

I haven’t tried those, but they look right. Of course, they won’t work in the FCC challenge because that is looking for specific things.