Add caveat to React.createContext docs
Addresses https://github.com/facebook/react/issues/13346
Deploy preview for reactjs ready!
Built with commit 5d6849536fd14121993ab87d443e48c2382d7254
https://deploy-preview-1112--reactjs.netlify.com
I have found the peerDependencies isn't enough of a solution. Even with peer dependencies, my packages tend to have copies of those peer dependencies within the node_modules folder to satisfy devDependencies of the same packages so that unit tests can succeed. Inevitably, the singleton issue still surfaces.
Following an approach similar to what this post describes, I've now set up my context module to use a Symbol and store the singleton instance on global using that Symbol, and ensuring that no second instance is ever created.
Here's an example of a module that I am using that provides a context object:
import React from 'react';
const CONTEXT_KEY = Symbol.for('@jeffhandley/ui-context/Context');
const globalSymbols = Object.getOwnPropertySymbols(global);
const hasContext = (globalSymbols.indexOf(CONTEXT_KEY) > -1);
if (!hasContext) {
global[CONTEXT_KEY] = React.createContext();
}
export default global[CONTEXT_KEY];
This approach has allowed me to end up with multiple copies of my ui-context package across my project's monorepo (and multiple repos), without encountering any issues of the context Provider and Consumer not being linked.
I'm curious if others have found they've also needed to use global with a Symbol to get a true singleton of their React Context module.
I noticed this PR is still sitting open. It's surely quite stale at this point. Should it get closed out?