@connect + contextType breaks with React 16.6
See original GitHub issue(I can provide a reproducible example if there’s a simple test project that I can base it on.)
Essentially, I’m using React 16.6 and doing this:
const MyContext = React.createContext();
@connect(...)
class MyComponent extends React.Component {
static contextType = MyContext;
render() {
return <div>Hello {this.context}</div>;
}
}
ReactDOM.render(<MyContext.Provider value="world"><MyComponent/></MyContext.Provider/>, ...);
And it fails with an error. In my concrete example, the value isn’t "world"
of course, but it happens to be undefined
, so I’m getting a TypeError: cannot read property 'store' of undefined
here because context===undefined
. I guess if I were to pass "world"
as the context, it would instead fail the invariant
just below.
The problem is that the <Connect(MyComponent)>
component gets its context populated based on my static contextType
, even though it’s setting its own legacy context for the usual redux plumbing. But the new context takes precedence. This happens because <Connect(MyComponent)>
declares the legacy contextTypes
and additionally hoists the contextType
from the nested component. This is ultimately a bug in the hoist-non-react-statics
library and I have already sent a fix there: https://github.com/mridgway/hoist-non-react-statics/pull/62
Please let me know if you disagree with the fix. In case they don’t merge it soon, react-redux
could work around the issue by doing something like this (I can send a PR):
const hoisted = hoistStatics(Connect, WrappedComponent);
delete hoisted.contextType;
return hoisted;
Issue Analytics
- State:
- Created 5 years ago
- Reactions:3
- Comments:12 (6 by maintainers)
Top GitHub Comments
Until react-redux v6 is released the easiest workaround is to wrap component with contextType into function component
This is likely due to one of the known bugs in React where mixing legacy context and
createContext
cause things to work wrong. Also, while it may not be directly related, we don’t recommend or support usingconnect
as a decorator.If there’s an easy fix, we can potentially look at it, but otherwise my advice is to avoid using
contextType
on a component until React-Redux v6 is out, and you’ve upgraded to that.