kzg
kzg

Reputation: 780

React stateless components - how to organize inner functions?

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.

Upvotes: 6

Views: 1481

Answers (1)

Julius Breckel
Julius Breckel

Reputation: 434

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.

Upvotes: 7

Related Questions