6

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.

2
  • can you share why you don't prefer using function expression as main component function. example: const MyComponent = () => ( //your code...); Commented Jul 28, 2016 at 7:09
  • stackoverflow.com/questions/37288950/… - explanation Commented Jul 28, 2016 at 10:05

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.