简体   繁体   中英

prevent re render in child component in react js

I have a counter app. I need to prevent re-render component. I want to execute Childcompnent only when I clicking on update, but here it is executing both time when I click count or update.

import { useCallback, useMemo, useState } from "react";

export const App = () => {
  const [count, setCount] = useState(0);
  const [updatecount, setUpdateCount] = useState(0);

  const incCount = () => {
    setCount(parseInt(count) + 1);
  };

  const updCount = useCallback(() => {
    return setUpdateCount(parseInt(updatecount) + 1);
  }, [updatecount]);

  return (
    <>
      <button onClick={incCount}>count</button>
      <button onClick={updCount}>update</button>
      <Childcompnent count={count} />
      <p>{updatecount}</p>
    </>
  );

};

export default App;

export function Childcompnent({ count }) {
  console.log("pressed");
  return <p>{count}</p>;
}

Wrap your Childcompnent in React.memo :

const Childcompnent = React.memo(({ count }) => {
  console.log("pressed");
  return <p>{count}</p>;
});

Here is the sandbox:

编辑 serverless-wood-ro6iek

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM