Recently I've been seeing a lot of examples in blogs where the methods inside React functional components are given an underscore. I also saw this in class-based components and was told it meant they were private (?).
But functional component internal functions are already private and inaccessible outside of the component, right?
Example:
function MyComponent({ propOne }) {
const _getData() {
/// Why does this have an _underscore on it?
}
return (
<div>a div</div>
)
}
Go with functional if your component doesn't do much more than take in some props and render. You can think of these as pure functions because they will always render and behave the same, given the same props. Also, they don't care about lifecycle methods or have their own internal state.
There is no render method used in functional components.
Class Components vs Function Components:Class components need to extend the component from “React. Component” and create a render function that returns the required element. Functional components are like normal functions which take “props” as the argument and return the required element.
Nothing is better, because both have pros and cons. But class components are important to understand React flow and lifecycle methods. The new learner should practice React using class components. Once they are familiar with class components, they can learn and use functional components.
It's a naming convention that the Airbnb React/JSX Style Guide (version 2019.05.24) actually warns against:
- Do not use underscore prefix for internal methods of a React component.
Why? Underscore prefixes are sometimes used as a convention in other languages to denote privacy. But, unlike those languages, there is no native support for privacy in JavaScript, everything is public. Regardless of your intentions, adding underscore prefixes to your properties does not actually make them private, and any property (underscore-prefixed or not) should be treated as being public. See issues #1024, and #490 for a more in-depth discussion.
In short:
underscore
to denote private
methods is borrowed from other languages.private
and prevent its use.It's up to you whether to follow the convention or not. There's no need to. If you follow the style guide cited above, you shouldn't. However, it also depends on the people you work for / with, e. g. if the company uses a style guide with the leading underscore to denote private
properties.
Example for this convention in another language - Python. From the Naming Convention:
_single_leading_underscore
This convention is used for declaring private variables, functions, methods and classes.
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