3 ms·
To clarify: I'm surprised this article is on the front page because I find it unlikely there's genuine interest in this (relative to some of the other stuff tha
by pluma 9y ago
To clarify: I'm surprised this article is on the front page because I find it unlikely there's genuine interest in this (relative to some of the other stuff that's usually on HN) for a number of reasons.
First of all, it's a very short article that pretty much just consists of a list of fairly simple and specific trivia.
Secondly, it's an obvious promo for the author's commercial training services.
And finally the information is not very helpful: the cheatsheet is entirely irrelevant if you understand the React lifecycle because the lifecycle makes it obvious why you can or can't use setState:
* constructor: this is where you initialise a class instance, so obviously this is the one place writing to `this.state` is allowed (this is also the one exception you may want to memorise)
* componentWillMount, componentWillUpdate, componentWillUnmount: these exist to notify the component that rendering/unmounting is about to happen, so it's too late to make any state changes (also componentWillMount is generally discouraged in favour of constructor)
* shouldComponentUpdate, render: these should be side-effect free, so setState is obviously verboten
* componentDidMount, componentDidUpdate: these exist to notify the component rendering is finished, so state manipulation is now acceptable again -- but having setState her is still probably a bad idea because you just finished rendering the current state and it's weird to change the state because of that
* componentWillReceiveProps: this is the one place where it's sensible to call setState in the lifecycle because you have something sensible to react to (i.e. prop changes) but this likely means you have state that is just a representation of props, which again is discouraged
So in other words, you generally should avoid calling setState in lifecycle methods (rather than callbacks or directly setting state in the constructor).
The cheatsheet doesn't provide any of that information. In fact, for the people who would benefit from a cheatsheet of this level of abstraction, a simple picture with the following text on it would be far more useful:
DON'T call setState in lifecycle methods.
DO use this.state in constructors.
EDIT: One exception is componentDidMount because it can be used to make sure the code only gets executed on the client (rather than during server-side rendering). But again, the "article" doesn't include this information either.
- hungerstrike 9y agoYou use this.state in render() too.