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>;
}
CodePudding user response:
Wrap your Childcompnent
in React.memo
:
const Childcompnent = React.memo(({ count }) => {
console.log("pressed");
return <p>{count}</p>;
});
Here is the sandbox: