This repository was archived by the owner on Sep 21, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 109
This repository was archived by the owner on Sep 21, 2022. It is now read-only.
Support memoization of component functions during render phase #33
Copy link
Copy link
Open
Description
var Hello = React.createClass({
getExpensiveNumber: function() {
return ...; // expensive value computed from props and state
},
computeSomethingBasedOnExpensiveValue: function() {
return this.getExpensiveNumber() + 1;
},
render: function() {
return <div>Number is {this.getExpensiveNumber()}, next number is {this.computeSomethingBasedOnExpensiveValue()}</div>;
}
});
In the following example, we can see this.getExpensiveNumber()
is called twice during the render phase, which means the expensive code runs twice.
Current solutions for this execution cost problem are:
- Compute the expensive value only once at the beginning of the render method, and pass it to all rendering functions that needs it. In complex components this can lead to boilerplate and more complex method signatures.
- Perform the expensive computation in state, but this is not advised by React documentation as it duplicates the source of truth (and also introduce boilerplate).
Since React's render method is supposed to not have any side effect, and during the render phase neither props and state are supposed to change, another possibility is to be able to memoize the expensive render functions. During a single render phase, they are supposed to always return the exact same value (for primitives at least, it could be another object's identity...).
We could probably have a syntax like this one:
var Hello = React.createClass({
getExpensiveNumber: React.renderMemoized(function() {
return ...; // expensive value computed from props and state
}),
computeSomethingBasedOnExpensiveValue: function() {
return this.getExpensiveNumber() + 1;
},
render: function() {
return <div>Number is {this.getExpensiveNumber()}, next number is {this.computeSomethingBasedOnExpensiveValue()}</div>;
}
});
And this will memoize the function per render phase, meaning the expensive call will only run once per render instead of twice.
guilhermesimoes, gregsherrid, bendtherules and darkartur
Metadata
Metadata
Assignees
Labels
No labels