Class component bind vs. function component useCallback

82 views Asked by At

For comparison purpose I wrote same logic as class vs. function component, and noticed some behavioral differences.

Class component with bind:

this.logName = this.logName.bind(this);

then function component with useCallback:

const logName = useCallback(() => {
   console.log(`Name is - ${state.name}`);
}, [state.name]);

Inside these, I'm calling child component (wrapped in react.memo for performance):

import React, { useEffect, useState } from "react";

const ChildComp = (props) => {
  const [state, setState] = useState(0);
  useEffect(() => {
    console.log("child render");
    setState((state) => state + 1);
  }, [props]);
  return (
    <div className="child">
      <h4>Child Comp ({state})</h4>
      <button onClick={props.log}>Log Name </button>
    </div>
  );
};

//export default ChildComp;
export default React.memo(ChildComp, (p, n) => p.log === n.log);

Sandbox here

If I update age, due to react.memo it doesn't re-render child, it's expected and working fine in both, but if I update state.name in functional, child re-render (due to dependency in useCallback), but doesn't in class. Due to bind in class component I always get right value, but can't remove dependency ([state.name]) in functional, else I will get old value.

Please help me understand this. Do I need to optimize function component more to get same behavior as class (no child rendering even state.name update), and how can I do so?

0

There are 0 answers