Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 448
kzg Avatar asked Jul 27 '16 17:07

kzg


People also ask

Can stateless components have functions?

Stateless components are those components which don't have any state at all, which means you can't use this. setState inside these components. It is like a normal function with no render method. It has no lifecycle, so it is not possible to use lifecycle methods such as componentDidMount and other hooks.

Can a stateless component have props?

Stateful and Stateless Components Note that both types of components can use props. In the example, there are two React components.

What are the advantages of stateless components in React JS?

The answer is performance. Stateless functional components can be rendered faster. One of the reasons why this is the case is because stateless functional components do not require some of the life cycle hooks.


1 Answers

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.

like image 166
Julius Breckel Avatar answered Oct 01 '22 07:10

Julius Breckel