When should I use logic inside of render vs logic inside of the class declaration?

Question

When should I use logic inside of render vs logic inside of the class declaration?

Answer

When we have simple logic, think logic that is easy to read and understand, we can put it in our render function. If instead we have logic that we would not want to be re-created each time the render function is called, or logic that is harder to read/understand, think function definitions, event handler functions etc, we should put that logic inside the class declaration.

For example:

import React from 'react';
import ReactDOM from 'react-dom';

class MyNumbers extends React.Component {
  multiplySomeNumbers(n) { //We define the `multiplySomeNumbers` method inside our class declaration because we won't want `multiplySomeNumbers` to be re-created each time the render function is called. Also, if instead we defined this logic inside of `render`, it may be hard to read/understand or convoluted.
    if(n > 10) {
      return n * 5;
    } else if (n > 5) {
      return n * 10;
    } else {
      return n * 2
    }
  }
  render() {
    const n = Math.floor(Math.random() * 12 + 1); //We can keep simple logic like this inside our `render` method.
    return (
    	<div>
      	<h1>The starting number is {n}. After doing some calculations....the number is {this.multiplySomeNumbers(n)}. </h1> 
      </div>
    )
  }
}

ReactDOM.render(<MyNumbers />, document.getElementById('app'));
14 Likes

Should I think about function definitions as methods? Because actually I tried to write function inside the class definition, and I could not access it in my render() function. But it worked fine with method

1 Like

Perhaps another way to answer this question is to state that class definitions can only contain methods. Trying to put variable declarations or flow-control into a class definition is treating it as if it were a function, which would be incorrect.

Note that my answer here is in response to what the lesson was saying to watch out for, which was the declaration of a variable in the class definition.

8 Likes

use this.functionname to access a method in the same class
or
u can use method name instead of this. but it is inappropriate

1 Like