Skip to content

Conversation

@rtsao
Copy link

@rtsao rtsao commented Aug 9, 2018

@reactjs-bot
Copy link

Deploy preview for reactjs ready!

Built with commit 5d68495

https://deploy-preview-1112--reactjs.netlify.com

@jeffhandley
Copy link

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.

@jeffhandley
Copy link

I noticed this PR is still sitting open. It's surely quite stale at this point. Should it get closed out?

@rickhanlonii
Copy link
Member

Closing since this PR is for the old docs, but if you think this is still needed feel free to create a PR to add a caveat to the createContext docs.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

5 participants