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

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>
  );
}

Leave a Reply