Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Motoki Higa
Motoki Higa
14,111 Points

Components as function expression or function declaration or arrow function

Hi there, I am new to React, and this course has been great.

I have a question in regards to what type of functions to use. So far, I'm understanding the main difference between stateless components (functions) and stateful components (classes).

But, I am confused about in which situation to use Expression, Declaration or the Arrow when it comes to React components.

I think I have moderate knowledge about the differences between the 3 in pure JS. Such as hoisting situation, and how "this" works differently for arrow function.

However, I am not sure which is the best way to go for the stateless components in React..

I am in the early stage on this React course, so I might be able to find answer later on in this path, but I thought I might as well ask now to get some insight.

Thanks in advance!

1 Answer

Steven Parker
Steven Parker
231,153 Points

If you plan to use "this" inside a function, you probably don't want an arrow function since they don't establish a value for it. For more details and other differences between arrow functions and conventional ones, see this MDN page on Arrow function expressions.

Motoki Higa
Motoki Higa
14,111 Points

Thanks for your answer and the link! I will have a look and learn about it more. So, in this course, teacher tends to use arrow function throughout the lecture, so I am assuming using "this" in react components is not so common.

Also it would be nice to know how people choose function expression over function declaration or vice versa based on their reasons, especially in react.

Steven Parker
Steven Parker
231,153 Points

Technically, any anonymous callback is created with a function expression; whether conventional or arrow type. And the choice is probably best made with an awareness of the differences (like "this") and what will be needed in the body. "When in doubt, go conventional"