Cached state in render?
nicinabox opened this issue ยท 7 comments
Can you explain more about why Cached State in render is an antipattern? The example doesn't seem to show what's being cached and what problem arises from a variable assignment in render.
+1 on this! Does React do some optimization of components' render
functions to do partial runs in some cases? Or is this just a general pattern for abstracting logic out of the render
function for the sake of simplicity/maintenance?
There was a debate on twitter inspired this one. I'm wishing that I linked it as a reference.
At the end of the day, this is just a preference. We had some pretty gnarled render
functions and it was easy to draw the line at "if you're formatting stuff, use a getter function". It keeps diffs easy to read.
This also gets a lot nicer when used with actual getters and ES6 React.Component
:
class MyComponent extends React.Component {
get greeting () {
return `HI ${this.props.name.toUpperCase()}!`;
}
render () {
return <h1>{this.greeting}</h1>;
}
}
๐ Might be worth explaining that for future reference. ๐
Thanks for the explanation ๐
Thanks! Agreed, that one could use a little attention. I'll add some meat.
Moving forward, how do you both feel about ES2015-style examples over instead of ES5?
I'm in favor.
Hey folks, made an ES6 PR and added a note at the bottom of this section about how it's mostly stylistic for the purpose of more readable diffs. Would love any additional feedback there.
Thanks for helping us make this better :)