Is there any reason to prefer one of these methods to write stateless components?
export default function MyComponent(props) {
function myHelper() {
return "something";
}
return (
<p>
{myHelper()}
</p>
);
}
export default function MyComponent(props) {
const myHelper = () => {
return "something";
};
return (
<p>{myHelper()}</p>
);
}
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.
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.
Stateful and Stateless Components Note that both types of components can use props. In the example, there are two React components.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With