When researching contexts I've stumbled across a common pattern more than once:
const storeContext = React.createContext()
const Provider = (children) => {
const [state, setState] = React.useState();
const ctxValue = React.useMemo(() => [state, setState], [state]);
return (
<storeContext.Provider value={ctxValue}>
{children}
</storeContext.Provider>
)
}
Many people seem to use useMemoin this case, and I'm not sure why. At first glance, it seems to make sense since passing an object/array directly would mean that this object would get recreated on every render and trigger the children to be rerendered since a new reference is passed. At second glance, I struggle with the pattern.
I'm not sure how this pattern could potentially prevent any rerenders. If a component up the tree changes, all children (including the context) rerender anyway, and if state changes, the provider rerenders (rightfully) itself as well as all children.
The only thing that I see useMemo do is to save a tiny bit of memory since we're not recreating the ctxValue object on every render.
I'm not sure if I'm missing something here, and would love some input.