Skip to content

Remove context masking to allow pure intermediate components to implement a context aware shouldComponentUpdate - #7225

Closed
bvella wants to merge 2 commits into
react:masterfrom
ixaris:master
Closed

bvella wants to merge 2 commits into
react:masterfrom
ixaris:master

Conversation

@bvella

@bvella bvella commented Jul 8, 2016 •

Copy link
Copy Markdown

Same as #7213 but this time on master

I am using contexts to propagate locale and routing information. My problem is that some pure components stop subtree rendering when the context changes (because pure components only check state and props). This is a problem for many people as per issue #2517.

I reasoned that not masking the context for intermediate components would be better than masking, and the defined contextTypes would only be used for validating, not for filtering. For properties, components define propTypes, but they can still get properties that they do not define. The same reasoning can be applied to contexts, whereby through contextTypes, a component defines what it expects to be in the context, but not implying that nothing else can be in the context. i have updated the tests to reflect this update.

Since components that are not interested in context would typically not use the context argument, not masking the context would not cause any existing component to break, unless said components explicitly are checking that the context param is undefined. This would, however, create an opportunity for a refinement of pure component, say a ContextAwarePureComponent which would compare state, props and context in shouldComponentUpdate, allowing context updates to cause re-renders of pure components.

I am currently running in development with this patch, using radium and some react-bootstrap components, and did not experience any issue

@ghost

ghost commented Jul 8, 2016

Copy link
Copy Markdown

Thank you for your pull request and welcome to our community. We require contributors to sign our Contributor License Agreement, and we don't seem to have you on file. In order for us to review and merge your code, please sign up at https://code.facebook.com/cla - and if you have received this in error or have any questions, please drop us a line at [email protected]. Thanks!

@ghost

ghost commented Jul 12, 2016

Copy link
Copy Markdown

Thank you for signing our Contributor License Agreement. We can now accept your code for this (and any) Facebook open source project. Thanks!

@traviscooperjs

Copy link
Copy Markdown

This is great!

  1. Syncing up how context works with how props work ( with regards to propTypes) is awesome!
  2. Also, as you mentioned, makes it so intermediate components do not need to know which context props any of its children may need.

Exit Question: Would this make context a supported ( and documented ) feature of React?

@iclanzan

Copy link
Copy Markdown

@zpao

zpao commented Jul 14, 2016

Copy link
Copy Markdown
Contributor

cc @sebmarkbage @spicyj

@ghost ghost added the CLA Signed label Jul 14, 2016
@DarylCantrell

Copy link
Copy Markdown

I don't like this approach.

It forces every existing component to become "context aware". Every component which implements shouldComponentUpdate() now has to check context -- but check for what? If I'm writing a reusable component, it's impossible for me to know whether context changes are important to my child components and thus require a new rendering pass. The only safe thing to do is:

shouldComponentUpdate() {
    if (this.context !== nextContext) { return true; }
    // other checks
}

Since this is basically the only safe and proper way to implement shouldComponentUpdate() in the presence of context changes, why not just codify it? Make components always update if context changes.

Another approach would be to force parent components to update whenever any of their children are listening to contextTypes which get changed. That would avoid unnecessary updates, but I don't know how easy it is to implement.

@sebmarkbage

Copy link
Copy Markdown
Contributor

Yea, we don't want to do this for the reasons mentioned above.

An intermediate doesn't know what is in context and therefore it can't reason about what to compare in there. Doing any tests in there breaks the encapsulation. We need another way to circumvent intermediates.

Currently, the only really supported use of context is for static content and use of manual subscriptions to manage the updates.

@bvella

bvella commented Jul 22, 2016

Copy link
Copy Markdown
Author

@DarylCantrell even if

shouldComponentUpdate(nextProps, nextState, nextContext) {
    if (this.context !== nextContext) { return true; }
    // other checks
}

is the only safe way to implement this, this is still impossible to implement today, because the context is hidden from intermediates.

@sebmarkbage The same reasoning can be applied to props. A component defines propTypes the same way it defines contextTypes, so why doesn't react hide the properties that the component did not subscribe to? It seems to me that unknown props and unknown context should work in the same way. Higher order components depend on receiving properties that they do not know about so that they pass them on to their children. However this is impossible to do with context.

One thing one can do with this proposed update is to create a ContextAwareDecorator that compares the context(s) in use by that application, such that pure intermediate components that are decorated would have their shouldComponentUpdate() bypassed by the context check, something like the following:

function ContextAwareDecorator(Original) {
   return class extends Original {
        constructor() {
            super(...arguments)
        }
        shouldComponentUpdate(nextProps, nextState, nextContext) {
            return shallowEqual(this.context, nextContext) 
                && super.shouldComponentUpdate(nextProps, nextState, nextContext)
        }
    }
}

But again, this is impossible to do today, when using a pure reusable component that should re-render the children on context changes but does not

@jimfb

jimfb commented Jul 22, 2016 •

Copy link
Copy Markdown
Contributor

The same reasoning can be applied to props. A component defines propTypes the same way it defines contextTypes, so why doesn't react hide the properties that the component did not subscribe to?

No, a component can only receive props that were intended to be handled by that component. It never receives props that weren't explicitly passed to the component. Context is different because it is an ambient value. A component can't reason about the ambient value, unless it knows how to handle that value, in which case it can opt in by defining it in context types.

@sebmarkbage is correct; we need a way to circumvent intermediates.

But again, this is impossible to do today, when using a pure reusable component that should re-render the children on context changes but does not

No, it is not impossible. It's just a little painful. You can always pass a second context variable called myVariableName_onChange=[]. In componentDIdMount of all subscribers, you say this.context.myVariableName_onChange.push(this). Then, when you update your context variable, you always iterate through the subscriptions and do a forceUpdate (for(var component in myVariableName_onChange) component.forceUpdate()). Don't forget to unsubscribe in componentDidUnmount

That's not the only workaround, but it is one of many viable solutions. We totally understand that this is suboptimal and we want to find a better solution that circumvents intermediates, but we need to do it right. Breaking encapsulation will just make the migration harder in the future, as people start depending on details that we never meant to expose.

As Sebastian said:

Currently, the only really supported use of context is for static content and use of manual subscriptions to manage the updates.

@aweary

aweary commented Jul 22, 2016

Copy link
Copy Markdown
Contributor

Is it possible to stop passing automatically passing context to each component constructor and instead store it somewhere outside the component tree? Then contextTypes would be responsible for querying/including context at the component level?

@jedwards1211

Copy link
Copy Markdown
Contributor

@jimfb @sebmarkbage I know you must have created context masking for specific reasons in the first place, but I think it's worthy of debate, because it seems to me that the general React philosophy is a component should be able to know/control everything that affects it and its descendants, and context masking subverts that.

In your mind, what are the advantages/disadvantages of getting rid of context masking? Here is what I'm thinking:

Advantages:

  • no more intended updates prevented by pure mid-level components
  • no work done to mask context = better performance
  • easier to see what's on context for any subtree, in dev tools or otherwise

Disadvantages:

  • components could arbitrarly mess with context props not intended for them (but can't this happen anyway with props that have to be passed down through multiple levels?)
  • contextType checks could be bypassed

@jedwards1211

jedwards1211 commented Jul 28, 2016 •

Copy link
Copy Markdown
Contributor

I just realized another disadvantage that's more serious:

  • pure components all the way down to the bottom of the tree would get re-rendered on every context change, even if the context change was only relevant to an ancestor

@mslade-vcf

Copy link
Copy Markdown

Sorry if I'm a little late to the party, but I have a suggestion which doesn't appear to have been

Suppose there was a setContext() method that worked pretty much like setState(). Since (as far as I can tell) every component class needs to declare the context properties that it uses, React could keep track of which mounted components use which context properties, and thus which ones need to be notified of changes to the various properties, so setContext() would trigger an update of all of the components that use the changed context property/properties.

I am guessing my way through this so maybe there's something I'm missing.

I understand that some people might think this is overkill as context tends to be mostly read-only, and the kind of situations where context changes can generally be handled with a forced update of the whole DOM subtree.

@sophiebits

Copy link
Copy Markdown
Collaborator

React could keep track of which mounted components use which context properties

Yes, this would be possible but it would be slower than we'd like so we've decided against doing this by default.

@moodysalem

moodysalem commented Nov 11, 2016 •

Copy link
Copy Markdown

I like this solution because it also solves the problem of trying to render a component outside the DOM with the available context that I encountered here #8262

WRT to the following:

Since this is basically the only safe and proper way to implement shouldComponentUpdate() in the presence of context changes, why not just codify it? Make components always update if context changes.

Isn't this already the default behavior (i.e. codified)? You only define custom shouldComponentUpdate when you're optimizing performance and thus only need to be aware of context when you're optimizing performance.

And for most cases, PureComponent does exactly what you need it to do when you're trying to save time in the render-including a shallow comparison of context.

IMO context should just be treated as a prop that you don't have to explicitly pass down to the children

Edit again: this also gives you control over choosing not to try to rerender some part of the tree because of a context change when you know that none of the components underneath are using context

@moodysalem

moodysalem commented Nov 11, 2016 •

Copy link
Copy Markdown

I just realized another disadvantage that's more serious:

pure components all the way down to the bottom of the tree would get re-rendered on every context change, even if the context change was only relevant to an ancestor

In most use cases context rarely changes though as it contains references to functions or instances of classes

@wmertens

wmertens commented Feb 1, 2017

Copy link
Copy Markdown
Contributor

How about this approach: Treat context as an ambient value that affects everything, but doesn't necessarily re-render everything.

Context changes trigger a full re-evaluation of the tree: if your SCU returns false, that just means you won't re-render. All your children will be re-evaluated in any case.

Right now, the only way to get context changes everywhere is to add a key to the root element that changes when you want the context to apply, and that kills internal component state.

Making context behave in the way described above will make it work like people expect.

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.