-
Notifications
You must be signed in to change notification settings - Fork 47.9k
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
Deprecate componentWillMount Maybe? #7671
Comments
I mostly use cWM to perform setState based on initial props, since cWRP doesn't fire initially. I could do it in constructor, but I try and avoid extending that method when possible because I have an allergy to super calls :/ |
@yaycmyk If you could use field initializers would you use that instead? class Foo {
state = { data: this.props.initialData };
...
} or for something more complicated: class Foo {
state = this.computeInitialState();
computeInitialState() {
var state = { data: null};
if (this.props.something) {
state.data = this.props.somethingElse;
}
return state;
}
...
} |
for createClass cWM is the only place to do constructor stuff, since you can't actually define a constructor. I need to do a grep through some of our code bases I think there are a couple other use cases/optimizations that use it I'm not remembering |
@sebmarkbage I do use property intializers, though they become clumsy if you need a non-trivial amount of Boolean logic. To be fair, they do cover 95% of all my use cases. cWM is a rare sighting in our products |
For server rendering, componentWillMount fires but not componentDidMount. What would replace the browser-only nature of componentDidMount? Adding |
@mars |
I only use it to set up data structures on |
After looking back at my last app that used server-rendering, the only componentWillMount use case is an initial |
This issue is probably because of some of my recent hackery. Today, given that when http://codepen.io/anon/pen/gwbEJy?editors=0010 As a sort of DOM parallel, when you have a form that has two inputs where one of them is a button, then "keyDown" of a text input causes the form to submit. In other words, the presence or non-presence of another ancestor changes the behavior of another ancestor element. Also, radio groups. Not saying "keep componentWillMount" but it's a great way to create relationships between ancestors of a context. It would be nice to either 1) have a componentMountCancelled (sounds unlikely, or 2) call cDM on the server (???) because that's the only reason I do this in cWM or 3) have some first class API for building this kind of relationship between ancestors in the same context. I'd like (3), but have no idea what that looks like. For the use-case here, it's in the React Router v4 API: <div>
<Match pattern="/users" component={Users}/>
<Match pattern="/about" component={About}/>
<Miss component={NoMatch}/>
</div> If no Only reason this matters is server rendering. Thanks to some talks with @sebmarkbage we've got a plan B, but I am a little 😢 about this. (I think we might get a flicker when we move to cDM ... which is not exciting.) I'm pretty sure @kenwheeler's new |
@ryanflorence Why not just extend constructor in that case though? cDM is really a last resort since it's way less efficient from needing a second render pass. |
Would there ever be a case where we'd need to compute some data or perform a certain routine before the component mounts, that we otherwise wouldn't be able to do in the component constructor? What if we needed or wanted to fire off a Redux action before the component mounts for the first time? Or what about wanting to attach an event listener to the component before it mounts? I'm just worried that there might be some niche use cases for @ajwhite I'm curious what you think about this |
@nickzuber I was just coming to mention this. I work on a rails app that uses react-rails for server rendering a collection of smaller react/redux client apps. A pattern that is working well for us is to dispatch actions that populate our reducers with initial data in |
@ryanflorence This is more in response to Fiber and implementing For your use case, you don't really need |
@aflanagan Can you use the field initializer pattern (or constructor) that I used above to initialize the state from the props? |
@sebmarkbage ah yes, I think we could do that. We adopted the |
To help tackle the server use case, what about a new method like componentDidRender? For the browser lifecycle, it'd come before cDM. The idea being the JSX has been rendered/"compiled" into vdom but not yet mounted somewhere. |
There is one use case, that is also the same as the only use case for For example, if the children rendering causes the scroll position of a page to change. class ScrollRestore {
componentWillMount() {
this._scroll = Global.scrollTop;
}
componentDidMount() {
Global.scrollTop = this._scroll;
}
componentWillUpdate() {
this._scroll = Global.scrollTop;
}
componentDidUpdate() {
Global.scrollTop = this._scroll;
}
...
} Technically, you can do the same thing in the constructor but it is kind of iffy to have impure constructors. |
Just wanted to chime in that |
Airbnb's primary use cases for All of our translations will break in the former case, if this lifecycle method is deprecated. Since we primarily handle phrases at the top level of a tree, ordering nondeterminism is not a concern for us. In addition, constructors should never have side effects - |
Thought this GitHub search might be useful to see some use cases, sorted by recently indexed so it represents how people are actively using componentWillMount in the wild today. Note: You must be logged in to search for code across all public repositories |
@ljharb So, it's basically lazy initialization of global state. We do a lot of lazy initialization in I guess you assume that props will never change and that you won't ever have two different subtrees with different phrases. Otherwise, people normally use Given that there are already a lot of assumptions involved in this particular use case, maybe it's not that bad to just do it in the constructor as a hack? How do you do this server-side? Do you assume that the context is only used for a single request at a time? No async rendering? |
I'd very strongly prefer something besides the constructor. Hmm, I thought Yes, that's right - whether it was async or not, it would be re-evaluated and reconstructed in a new |
If |
Adding a consistent lifecycle method to handle props would be super useful in many cases. The most common being "fetch the x for this.props.xId". The benefit of running before render is that you can show a loading indicator without requiring a second render. The problem is that for some use cases you'd want it to run on the server, like @ljharb's, but for the fetching data you'd want that on only client in most cases. Edit: maybe this should branch out to another issue. |
Is there ever a time (in the browser context) where componentWillMount is not called immediately after the constructor? As far as I can remember, componentWillMount is effectively a constructor function. It served that purpose before ES6 classes were adopted that came with their own constructors. In fact, in much earlier versions of React, componentWillMount was always called on construction IIRC which made server rendering painful. So we changed componentWillMount to be called only in the browser render context, and not in the server render context. (Then getInitialState was the effective constructor) All the uses I've seen for componentWillMount are just constructors which you expect to only run in the browser. If componentDidMount isn't the right place to move that code (due to double render) then moving it into the class constructor with a I don't see the reason to be concerned about doing side effects in a React component constructor if you're not concerned about doing the same within componentWillMount which is part of component construction. Since user code never instantiates components directly (library code does), the typical reasons to avoid side effect constructors doesn't apply for React components. Sebastian, maybe another option is to slightly change the behavior of componentWillMount rather than remove it by making it more explicitly part of construction just to avoid user code writing that browser check and preserve the majority of existing code? Would that be possible within Fiber? |
@jpdesigndev i'm not sure why it would be; |
Sorry, @ljharb, I wasn't clear enough. const SomeParent = (props) =>
<div>
<Example />
<Example />
</div> If EDIT: for clarity (hopefully) class Example extends React.PureComponent {
componentWillMount() {
const { fetchAction, fetchStatus, dispatch } = this.props;
//
// Notice the conditional here.
// If this code were in a componentDidMount(), the fetchStatus would be null
// for both <Example /> renders by <SomeParent />
//
// By utilizing componentWillMount()
// The second componentWillMount() call has the new fetchStatus
// that was updated synchronously by the dispatched action from the first <Example />
// rendered by <SomeParent />
if (fetchStatus !== FETCH_STATUSES.LOADING && fetchStatus !== FETCH_STATUSES.LOADED) {
dispatch(fetchAction);
}
}
render() { ... }
}
const SomeParent = (props) =>
<div>
<Example />
<Example />
</div> |
That makes no sense to me - two elements should invoke two WillMounts. |
@jpdesigndev I would suggest to move data fetching away from components, keeping only data fetching request dispatching in them. See redux-saga. |
@jpdesigndev Sorry I meant the logic for checking if the fetch is in progress and ignoring the request. |
@jpdesigndev In your example, the difference is that in One solution would be read the |
@ljharb @sompylasar @acdlite Thank you all for the thoughts/recommendations! @sompylasar Leaving this logic at the component level can, sometimes, make sense. For example, if the component really should be in control of fetch/re-fetch. Without some @acdlite Thank you for the explanation. That really helps clarify my thoughts on why I'm really just chiming in here to lay out a use case (which seems valid) for Thus far the proposed better/alternative ways are:
I'm perfectly willing to change my mind on this. Perhaps, I will be forced to do so if Also, have I missed the point entirely? Should I already be devising a way to migrate away from |
@jpdesigndev Then you have two actions: "fetch" (that leads to auto-cache and no re-fetch) and "refetch" (that leads to resetting the cache, stopping all previous requests, and re-fetching). |
|
Could you give more details about this? Is there any edge case? |
@NE-SmallTown Take a look at link above |
Let's use this thread to discuss use cases for componentWillMount and alternative solutions to those problems. Generally the solution is simply to use componentDidMount and two pass rendering if necessary.
There are several problems with doing global side-effects in the "componentWill" phase. That includes starting network requests or subscribing to Flux stores etc.
It is confusing when used with error boundaries because currently
componentWillUnmount
can be called withoutcomponentDidMount
ever being called.componentWill*
is a false promise until all the children have successfully completed. Currently, this only applies when error boundaries are used but we'll probably want to revert this decision and simply not callcomponentWillUnmount
here.The Fiber experiment doesn't really have a good way to call
componentWillUnmount
when a new render gets aborted because a higher priority update interrupted it. Similarly, our sister project ComponentKit does reconciliation in threads where it is not safe to perform side-effects yet.Callbacks from
componentWillMount
that update parent components with asetState
is completely unsupported and lead to strange and order dependent race conditions. We already know that we want to deprecate that pattern.The reconciliation order of children can easily be dependent upon if you perform global side-effects in
componentWillMount
. They're already not fully guaranteed because updates can cause unexpected reconciliation orders. Relying on order also limits future use cases such as async or streaming rendering and parallelized rendering.The only legit use case for
componentWillMount
is to callthis.setState
on yourself. Even then you never really need it since you can just initialize your initial state to whatever you had. We only really kept it around for a very specific use case:When the same callback can be used both synchronously and asynchronously it is convenient to avoid an extra rerender if data is already available.
The solution is to split this API out into a synchronous version and an asynchronous version.
This guarantees that the side-effect only happens if the component successfully mounts. If the async side-effect is needed, then a two-pass rendering is needed regardless.
I'd argue that it is not too much boilerplate since you need a
componentWillUnmount
anyway. This can all be hidden inside a Higher-Order Component.Global side-effects in
componentWillReceiveProps
andcomponentWillUpdate
are also bad since they're not guaranteed to complete. Due to aborts or errors. You should prefercomponentDidUpdate
when possible. However, they will likely remain in some form even if their use case is constrained. They're also not nearly as bad since they will still get theircomponentWillUnmount
invoked for cleanup.The text was updated successfully, but these errors were encountered: