If value is an object, then useContext will cause re-rendering

Viewed 277

To prevent unnecessary rendering, I split the Context into two parts, one for the state reference system and one for the update system. This way, even if the state is changed, the component using the update handler will not be re-rendered.

However, we were not able to confirm the expected behavior. The reason is that when we passed the value to the provider, we passed it as follows

 <Component.Provider value = {{ hoge, foo }}> 
  {children}
 </Component.Provider> 

Passing the value as an object to value will disable memoization. However, I found that many codes on the net pass the value as an object.

If it is possible to pass it in the form of an object, I would like to know how to do so. Perhaps it is difficult to do so. ....

import React, { createContext, useContext, useState } from "react";

const CountStateContext = createContext<any>({});
const CountDispatchContext = createContext<any>({});

function CountProvider({ children }: { children: React.ReactNode }) {
  const [count, setCount] = useState(0);

  return (
    <CountStateContext.Provider value={{ count }}>
      <CountDispatchContext.Provider value={{ setCount }}>
        {children}
      </CountDispatchContext.Provider>
    </CountStateContext.Provider>
  );
}

function Count() {
  console.log("render Count Component");
  const { count } = useContext(CountStateContext);

  return <h1>{count}</h1>;
}

function Counter() {
  console.log("render Counter Component");
  const { setCount } = useContext(CountDispatchContext);

  return (
    <>
      <button onClick={() => setCount(1)}>+</button>
    </>
  );
}

export default function App() {
  return (
    <CountProvider>
      <Count />
      <Counter />
    </CountProvider>
  );
}

0 Answers
Related