5

Is there any reason to prefer one of these methods to write stateless components?

  1. Function declaration with inner function declarations

export default function MyComponent(props) {
  
  function myHelper() {
    return "something";
  }
  
  return (
    <p>
      {myHelper()}
    </p>
  );
       
}
  1. Function declaration with inner function expressions:

export default function MyComponent(props) {

  const myHelper = () => {
    return "something";
  };

  return (
    <p>{myHelper()}</p>
  );
        
}
  1. Function declaration with external function declarations:

function myHelper() {
  return "something";
}

export default function MyComponent(props) {

  return (
    <p>
      {myHelper()}
    </p>
  );
           
}

I don't prefer using function expression as main component function, so I skipped those possibilities.

Is there any performance issue with one of these approaches? Or any other reason to use one above others?

Method 3. is easier to test, because I can write helpers as pure functions, export them and import in tests file. But there is the only argument I can find.

kzg
  • 690
  • 8
  • 19
  • can you share why you don't prefer using function expression as main component function. example: `const MyComponent = () => ( //your code...);` – Galeel Bhasha Jul 28 '16 at 07:09
  • http://stackoverflow.com/questions/37288950/why-does-the-airbnb-style-guide-say-that-relying-on-function-name-inference-is-d - explanation – kzg Jul 28 '16 at 10:05

1 Answers1

7

I think Method 3 would be the best, as the helper would only be created once and executed multiple times, on every render call. Whereas in the other cases the helper would be created every time the component is rendered, leading to possible performance problems.

Another point in favor of Method 3 is the testability you mentioned.

Julius Breckel
  • 404
  • 3
  • 13
  • 1
    On the other hand writing functions as inner declarations/expressions makes them private. As private functions it is clear they aren't meant to be accessed elsewhere. Though I guess the fact that they aren't exported already takes care of that. I have to say this question seems highly opinionated. – Waltari Jan 21 '20 at 12:07