Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React.js - using property initializers for all component methods

I am working on a React Native project and I'm using ES6 classes for React components.

Since React components defined via ES6 classes don't have autobinding, the React team recommends combining ES7 property initializers with arrow functions to create the same effect.

In order to be consistent and prevent confusion with this-binding, I am using ES7 property initializers for all component methods:

class Foo extends React.Component {
  constructor(props) {
    super(props);
    ...
  }

  componentDidMount = () => {
      ...
  };

  bar = () => {
    ...
  };

  render = () => {
    ...
  };
}

I was wondering -- are there any serious performance caveats to be aware of? In particular, I'm wondering about the render() method.

Overall, does this seem like a good approach?

like image 843
ender672 Avatar asked Mar 03 '16 00:03

ender672


People also ask

How do you pass static data in React JS?

The first approach is to pass the state data from parent to child component, as explained below. Create the static data into the state object like this. And pass the state values to the child component as demonstrated below. From the child component, it could be accessible as props .

What is a property initializer?

The new class “property initializers” allows you to define methods (or any property) in your React components using regular ES6 classes without worrying about binding.

Do you need to add key property on Reactjs elements?

Here's the rule: Whenever you're rendering an array of React elements, each one must have a unique key prop. It's only a problem if I try to pass the elements as an array.


Video Answer


1 Answers

The biggest caveat is that this particular feature is not standard nor agreed on yet. (It won't be ES7 since there is no ES7. Maybe ES2017 but still unclear.)

There is also a cost to allocating several new long lived objects and storing them on the class.

I wouldn't recommend this. Just for callbacks.

like image 106
Sebastian Markbåge Avatar answered Sep 21 '22 06:09

Sebastian Markbåge