I've seen code like this
function abc(){
return 'abc'
}
class MyComponent extends React.Component {
static abc = abc;
render() { return <h1>{this.abc}</h1>; }
}
where function abc
is defined outside of a react class. I have no clue why the author did it that way, why can't just do it within the class?
With the addition of Hooks, Function components are now almost equivalent to Class components. The differences are so minor that you will probably never need to use a Class component in React. Even though Function components are preferred, there are no current plans on removing Class components from React.
Functional components are nothing new in React, however it was not possible before version 16.8.0 to create a stateful component with access to lifecycle hooks using only a function. Or was it? Call me a pedant (many people already do!) but when we talk about class components we are technically talking about components created by functions.
If there is a constructor () function in your component, this function will be called when the component gets initiated. The constructor function is where you initiate the component's properties. In React, component properties should be kept in an object called state.
Functional Component: Write functions inside or outside the component? I often wrote functional components following a 'Class architecture' where all my function that concern the component are written inside of it like a method in a class. For example, I have here a function counterAsFloat that is related to the Counter component.
These are ES6 static methods and are not exclusive to React. They are members of the component class and not of instances of the component. They are not used extensively in React, but they can be useful. It is even mentioned in the React docs:
Sometimes it’s useful to define a static method on a React component. For example, Relay containers expose a static method getFragment to facilitate the composition of GraphQL fragments.
They can be used as common members of the Component, shared by all instances of it. To give you an idea, other static members of a React class are displayName
and defaultProps
.
Also see Static methods in React. As you can see, there aren't many cases where you would use a static method.
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