Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Static methods in React

I was looking through the React documentation and ran into the static method. I Was wondering in what sort of scenario it might be useful and couldn't think of any.

Is there a specific scenario in which static methods are useful when building components in React?

like image 843
ramesh Avatar asked Mar 31 '16 12:03

ramesh


People also ask

What are static methods in React?

The statics object of our React view components is meant to contain values or functions that can be accessed at any time without needing an instance of that component created.

What are static methods in JS?

Static methods are often utility functions, such as functions to create or clone objects, whereas static properties are useful for caches, fixed-configuration, or any other data you don't need to be replicated across instances.

What are static methods?

A static method (or static function) is a method defined as a member of an object but is accessible directly from an API object's constructor, rather than from an object instance created via the constructor.

What is static class React?

Static properties are properties of a class, not of an instance of a class.


1 Answers

defaultProps and propTypes are static members of React components, they do not change for every instance. See https://facebook.github.io/react/docs/reusable-components.html

One example for static properties is to be able to track how many instances of an object were created (not React specific). Note that most of the time, static methods are a code smell if you are modifying state.

var Contacts = React.createClass({
  statics: {
    instanceCount: 0
  },
  getInitialState: function() {
     Contacts.instanceCount++
     return {};
  },
  render: function() {
    return (<div > Hello {
      this.props.name
    } < /div>);
  }
});
console.log(Contacts.instanceCount) // 0
ReactDOM.render( < Hello name = "World" / > ,
  document.getElementById('container')
);
console.log(Contacts.instanceCount) // 1

Another example is a way to store constants.

var Contacts = React.createClass({
  statics: {
    MAX_VALUE:100
  },
  render: function() {
    return (<div > Hello {
      this.props.name
    } < /div>);
  }
});

if (someValue > Contacts.MAX_VALUE) {

}
like image 86
Juan Mendes Avatar answered Oct 11 '22 13:10

Juan Mendes