1

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>;
}
6
  • You're not using ChildComponent in your parent component. Why don't you want it to re-render? Here's some documentation on how to create a React snippet. Perhaps you could update your question using those steps. Commented Aug 27, 2022 at 12:00
  • Why would you not want to re-render? Please clarify and make sure this isn't an xy problem Commented Aug 27, 2022 at 12:04
  • means i want to execute childcomponent only when i clicking on update , but here it is executing both time when i click count,update Commented Aug 27, 2022 at 12:08
  • Apologies to the user who edited the question and who I called out. I hadn't realised that the <pre> tags were screwing up the formatting. Your edit was fine. Commented Aug 27, 2022 at 12:13
  • @Andy how do you know its <pre>? Commented Aug 27, 2022 at 12:19

1 Answer 1

1

Wrap your Childcompnent in React.memo:

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

Here is the sandbox:

Edit serverless-wood-ro6iek

Sign up to request clarification or add additional context in comments.

2 Comments

Yeah i got the solution . is any other means can i get the same output by using useCallback method?
No. React.memo is used to wrap React Function components to prevent unnecessary re-renderings. The useCallback is used to memoize functions.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.