Exercises 3/7 and 4/7 put calculation inside render function or before creating component class?


In the exercise, 3/7: Put Logic in a Render Function, the lesson says "A render function can also be a fine place to put simple calculations that need to happen right before a component renders. Here's an example of some calculations inside of a render function". A "simple calculation" is placed inside the render function:
var n = Math.floor(Math.random()*10+1);

However, in the very next exercise 4/7: Use a Conditional in a Render Function, a very similar calculation is done outside (and before) the call to create the component class:
var fiftyFifty = Math.random() < 0.5;

  • When would one want to include such a calculation inside the render function (as in 3/7)?
  • When would one want to include it before (as in 4/7)?
  • Is one or the other a best practice?

The two exercises seem contradictory or at least don't explain why to do it one way or the other.

Thanks in advance!


What defines best practice, in this case? Readability? Caching for re-use? This (4/7) example could be done either way, but given there is some control flow logic, the cached value is more readable.


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.