Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add caveat to React.createContext docs #1112

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open

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?

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.

4 participants