score:0

Accepted answer

a) memoizing is always faster in my tests (despite some blog posts saying otherwise). having said that you're not going to see any noticeable gains unless you have a particularly heavy component, or the component is rendering lots of children. it could also save you from loosing focus if you're typing and that input gets re-rendered because the parent does.

b) in short none of them will work, react.memo has to sit outside the render function, it's not part of the "magic" use hook functions which maintain references. you have to use usememo for inside render. here's an example: the components which don't re-render every second are ccomponent and dcomponent:

const ccomponent = react.memo(({ count }) => (
  <p>not re-rendered every second: {count}</p>
));

const maincomponent = (props) => {
  const acomponent = react.memo(() => (
    <p>re-render when parent does: {props.count}</p>
  ));

  const bcomponent = react.memo(({ count }) => (
    <p>re-render when parent does: {count}</p>
  ));
  
  const dcomponent = react.usememo(() => (
    <p>not re-rendered every second: {props.count}</p>
  ), [props.count]);

  return (
    <div>
      <acomponent />
      <bcomponent count={props.count} />
      <ccomponent count={props.count} />
      {dcomponent}
      <p>parent count: {props.count}</p>
      <p>parent anothercounter: {props.anothercounter}</p>
    </div>
  );
};

function app() {
  const [count, setcount] = react.usestate(0);
  const [anothercounter, setanothercounter] = react.usestate(100);

  react.useeffect(() => {
    const h = setinterval(() => {
      setcount((c) => c + 1);
    }, 6000);
    const h2 = setinterval(() => {
      setanothercounter((c) => c + 1);
    }, 1000);
    return () => {
      clearinterval(h);
      clearinterval(h2);
    };
  }, []);

  return (
    <div classname="app">
      <maincomponent count={count} anothercounter={anothercounter} />
    </div>
  );
}


reactdom.render(<app />, document.queryselector('#container'));
<script src="https://unpkg.com/react@17/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@17/umd/react-dom.production.min.js"></script>
<div id="container"></div>

score:0

i used the memo in a little experiment, i upload the pictures maybe it will be useful.

title.js:

title.js description

app.js:

app.js description


Related Query

More Query from same tag