Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to stop re-rendering of child component if parent update the context or state in react js?

how to stop re-rendering of child component if parent update the context or state in react js ?

I am already using React.memo still it is re-rendering.

this is my child component

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const Ab = () => {
  console.log("---ff-ddd");
  const pageContext = useContext(PageContext);

  useEffect(() => {
    setTimeout(() => {
      pageContext.updateGlobalMenu({});
    }, 5000);
  }, []);
  return <div>ddd</div>;
};

export default React.memo(Ab);

I am updating the context. I want it update the context value but not re-render the child component

export default function IndexPage() {
  const [globalMenu, setGlobalMenu] = useState("");

  const updateGlobalMenu = (menuContent) => {
    setGlobalMenu(menuContent);
  };

  return (
    <PageContext.Provider
      value={{
        updateGlobalMenu
      }}
    >
      <Ab />
    </PageContext.Provider>
  );
}

here is my code

https://codesandbox.io/s/friendly-bartik-3cnqvf?file=/pages/index.js:156-470

if you see it print two times console. it means it is re-rendering two times

>Solution :

If PageContext‘s value changes, then any component consuming that context (including Ab) will render. React.memo cannot stop this. In your case you’re changing the value on every render, so you have room to improve it by memoizing the context value. That way, the value won’t change unless it needs to:

export default function IndexPage() {
  const [globalMenu, setGlobalMenu] = useState("");

  const updateGlobalMenu = useCallback((menuContent) => {
    setGlobalMenu(menuContent);
  }, []);

  const value = useMemo(() => ({
    updateGlobalMenu
  }), [updateGlobalMenu]);

  return (
    <PageContext.Provider value={value}>
      <Ab />
    </PageContext.Provider>
  );
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading