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>
)
}
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:
The underscore to denote private methods is borrowed from other languages.
It doesn't change the method itself.
It's to show that the method is meant to be 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.
_functionName doesn't mean private, it is just a best practice.
If are interested in writing custom hooks react document suggest to prefix "use" before hook name ex: useCustomeHook https://reactjs.org/docs/hooks-custom.html
Functional component is a tiny function which accepts only props and return HTML in ReactJs.
Just as Jeanne Dark said, it's just a naming convention. It's up to you of course how to type your code, but I would not recommend using the underscore prefix, as you can see for yourself that the function is private without the underscore.
You can read about JS naming conventions here on W3 schools, or maybe even more trustworthy, googles JavaScript style guide.
Related
In our React codebase I see private in front of almost every functions in all the components. This is a class component. eg:
private componentDidMount() {
this.props.onLoad(false)
}
private UNSAFE_componentWillReceiveProps(
nextProps: Partial<IAdminPortalDispatchCarrierProps>,
)
What's the idea here? When would these methods be used publicly?
private is a typescript modifier, that makes these functions only accessible from inside the class. By marking something as private, typescript will give you a compile time error if you attempt to use the private function from outside the class. This lets you communicate to the other developers (including future-you) which pieces of code are meant for public consumption, and which ones are internal implementation details.
For the specific functions you listed though, I suggest making them public, not private. React lifecycle hooks must be called from outside the class to do their job. Specifically, they get called by react's internal code. Fortunately, typescript gets removed when compiling, so react is able to call your private functions regardless. But the misleading modifiers may lull you into a false sense that these functions are not being called.
I'm trying to figure out what is the purpose of introducing something called custom hooks when its just a function. If I take the following example https://medium.com/from-the-scratch/react-custom-hooks-a-simple-intuition-if-you-still-cant-hit-it-off-8d27fa4ba10, if I don't use the use prefix for the hook, it all still works fine. With the introduction of this terminology called custom hooks I'm not sure whats the purpose of it, or should I just go on using standard functions.
What is the main advantage I get when using the use prefix for a custom hook or function apart from some simple linting features?
What is the main advantage I get when using the use prefix for a
custom hook or function apart from some simple linting features?
Reasons are stated in docs:
Do I have to name my custom Hooks starting with “use”? Please do. This
convention is very important. Without it, we wouldn’t be able to
automatically check for violations of rules of Hooks because we
couldn’t tell if a certain function contains calls to Hooks inside of
it.
In very basic words: You can reuse stateful logic between components, witch is not possible with regular functions. I would suggest that you read the documentation, because ReactJS has a pretty good one :)
Stay safe
Nothing. There is no difference between them. useFoo function is just a function. In source code, it was not dealt with specially. It is just little bit complicated, but no difference between regular functions.
use prefix is just a term, or just culture, whether you obey it is entrusted to you. Of course, obeying the culture bring us good result. But this and that have no connection. Custom hooks are just functions.
Looks like functions which are part of the React framework are referred to as "methods":
"The only method you must define in a React.Component subclass is called render()."
https://reactjs.org/docs/react-component.html
However, this excerpt is from further down in the same webpage:
"The render() function should be pure, meaning that it does not modify component state"
So even in the same webpage on the official React website, render() seems to be referred to as either a function or a method. Do you use any guidelines for using the term "function" vs "method" when discussing these constructs in React? Or in the React world are these two terms completely interchangeable with no real discernment or nuance?
Do you use any guidelines for using the term "function" vs "method" when discussing these constructs in React?
No guidelines between referring to them either way because both terms are correct. However, I tend to hear render function more instead of render method from my experience.
It's most preferable for using the term "method" when explicitly mentioning/referring to "Class" or "Object" as in the case of the sentence the React docs used:
The only method you must define in a React.Component subclass is called render()
Still, it's up to preference regardless.
For reference on what a method is from MDN:
A method is a function which is a property of an object
https://developer.mozilla.org/en-US/docs/Glossary/Method
Generally the term "method" is used when describing a function that belongs to an object or class.
To use the term function is always correct, the reason react often uses the term "method" is because in react the code is often running inside of a class.
See What's the difference between a method and a function?.
In React, we usually talk about "method"s when we want to refer to a function in class component, like lifecycle methods.
Otherwise, it's just a normal function (arrow function included).
Don't get confused between the terms function and function component as they are not the same.
Seems like they're the same thing. Here's my conjecture for why people use both:
In class-based object oriented programming, the term "function" doesn't exist. Only "method". a public method, a private method, getter vs setter methods, etc.
In Javascript, the same concept has always been known as "function".
Javascript isn't originally a class-based object oriented programming language, although there are ways to make it that way. React, makes JS a class-based OOP.
So people who use the term "function" adopt a language that used to have "functions" but is now suddenly a class based object-oriented language in which you're supposed to have "methods", and the writers of the docs aren't opinionated and meticulous enough to set a standard, so they use both terms interchangeably and it leads to this confusion.
New to ReactJS. Got this on a "join reactJS event questionary" but was unable to compile it. It seems to be missing a React Component class definition for the Item and List.
Is this shorthand style valid?
Is this shorthand style valid?
yes, it is valid code, List and Items are Stateless functional components
In order to run this code you need use babel with babel-preset-react
Yes, they are stateless functions, aka "pure components". They take their props as their only parameter and return the render results. If you do not need to keep track of any state, they are very lightweight both to understand mentally and in terms of the resources needed by React to manage them.
As to why you were unable to compile it, possibly you do not enable the right ES6/ES2015 features in whichever compiler you're using. You are using among other things super calls, object destructuring (in the parameters) and arrow functions. For help with this, provide the specific error message.
It is a valid javascript es6 code, except that multiple dynamic children (here the list of Items) need to have key prop https://facebook.github.io/react/docs/multiple-components.html#dynamic-children
Is there a way to create a private method in XBL?
--update
The only documentation on MDN says nothing about private methods, but it's a wiki that's not always complete..
The answer to your question is that XBL does not support private methods. However, this doesn't mean that you simply have to leave your public methods openly exposed and just accept this situation without a fight. there are some options that you have at your disposal that can help communicate that a method is private or help discourage using or modifying them:
Use an underscore in method names:
Mozilla recommends using an underscore to mark methods and fields as private. Additionally, many JavaScript libraries use underscores in the methods that the developers wish to mark as private. Although a novice developer could ignore this and still invoke the method, most people who have some basic experience with JavaScript libraries, Firefox Extension development, or JavaScript in general should know what you mean when you have a method preceded by an underscore.
Use inheritance to hide private methods:
Out of sight, out of mind.
In some languages, functionality that is common to a series of subclasses is oftentimes moved to a base abstract class. In the subclass, the inherited methods won't be seen in the subclass code.
Although this is definitely not "private", you could encapsulate your "private" methods in an XBL binding and place your public methods in an XBL binding that extends the parent binding. Inheritance is one of the most powerful features of XBL, and this could help protect your private methods from being used simply because they won't appear in the XBL binding the developer is directly interacting with.
You could then put extensive comments in the parent that describes the purpose of the "private" functionality and that it isn't meant to be public.
Keep in mind that even if you could mark a method as private, this still won't stop someone who is determined. One could still simply mark the method as "public" and use it anyway.
Here is documentation on XBL, which asserts that methods are private, and also discusses inheritance:
https://developer.mozilla.org/en/XUL_School/Custom_XUL_Elements_with_XBL