When should I assign a variable to a JavaScript expression that I want to use in a JSX expression?

Question

When should I assign a variable to a JavaScript expression that I want to use in a JSX expression?

Answer

The use of variables to store JavaScript expressions will largely be based on preference. However, we will usually want to use variables assigned to our JS expressions when our JS code would otherwise be hard to read/follow before using our JS expression inside of our JSX.
For example:

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

ReactDOM.render(<h1>two + two = {2 + 2}</h1>, document.getElementById('app')); //Here, the JavaScript expression `2+2` is easy to read and understand what's going on in the code

vs.

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

const myFunc  = (a, b) => {
  //do some logic or calculations with parameters here
}


ReactDOM.render(<h1>{myFunc(3,4)}</h1>, document.getElementById('app')); //Here, we assign a function to the variable `myFunc` then call the myFunc fuction from inside our JSX - this is especially useful if the logic inside myFunc would be difficult to read and understand from inside a JSX expression
10 Likes