How to implement shouldComponentUpdate with this.context?
Problem
I know `this.context` is not officially there but quite a few libraries rely on it, and it seems like it's getting into shape with #2509. I'm trying to understand how exactly `shouldComponentUpdate` is supposed to be implemented with `context` in mind. I noticed it accepts a third argument (`nextContext`) and I can extend `PureRenderMixin` to also check it: [code block] Components that don't opt into `this.context` by not omitting `contextTypes` will not get this third argument, which is understandable. However this presents a problem when we have a `<Middle />` component in between between `<Top />` context owner and `<Bottom />` context consumer. If `<Middle />` implements a restrictive `shouldComponentUpdate`, there is no way for `<Bottom />` to react to `<Top />`'s context updates at all: (fiddle) [code block] The same problem would occur if I tried to give `Middle` a generic context-aware `shouldComponentUpdate` as I wrote above, because `Middle` has no `this.context` unless it opts in. This is possible to work around by adding `contextTypes` to `Middle`, but it doesn't look like a good solution. You'd need to explicitly add necessary `contextTypes` on every level with smart `shouldComponentUpdate` so it's too easy to slip up. Will this be solved by #2112? Is there another solution in the meantime? What is the recommended way?
Unverified for your environment
Select your OS to check compatibility.
1 Fix
Solution: How to implement shouldComponentUpdate with this.context?
I wonder if context propagation could happen in a separate tree traversal, without being blocked by falsy `shouldComponentUpdate` in the middle? Basically, when parent's context changes, it should mark all its descendants that receive this context as dirty, no matter how distant. Ancestor's context change should have the same effect as a state change for descendants who opt into this context—they
Trust Score
6 verifications
- 1
I wonder if context propagation could happen in a separate tree traversal, witho
I wonder if context propagation could happen in a separate tree traversal, without being blocked by falsy `shouldComponentUpdate` in the middle?
- 2
Basically, when parent's context changes, it should mark all its descendants tha
Basically, when parent's context changes, it should mark all its descendants that receive this context as dirty, no matter how distant. Ancestor's context change should have the same effect as a state change for descendants who opt into this context—they should receive new `context` regardless of what their parents said.
Validation
Resolved in facebook/react GitHub issue #2517. Community reactions: 15 upvotes.
Verification Summary
Sign in to verify this fix
Environment
Submitted by
Alex Chen
2450 rep