Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

static propTypes Vs React.PropTypes

Please do not close this question before reading completely. This may sound like a question which can be answered primarily by one's opinion. But why are there two implementations of PropTypes? Which one is preferred?

One way is to use static keyword and define our propTypes.

class App extends React.Component {   static propTypes = {     ...   } } 

The other way is to do something like this:

class App extends React.Component {   ... }  App.propTypes = {   ... } 

Can we remove the propTypes if we are using static keyword at the time of building app for production? Since removing propTypes is encouraged for performance gains.

like image 849
Mihir Avatar asked Sep 20 '16 06:09

Mihir


People also ask

Is PropTypes necessary in React?

One of the most important things when building React application is to make sure that the components receive correct props. Passing wrong props leads to bugs and unexpected behavior, so it's a good idea to warn developers about this as early as possible.

Is PropTypes deprecated?

PropTypes is deprecated since React 15.5.

Do you need React PropTypes with TypeScript?

Props are required in TypeScript In the prop-types package, all props are optional by default. To make a prop required, you will have to use . isRequired explicitly. With TypeScript, that is not the case.

Should I use PropTypes or TypeScript?

Typescript and PropTypes serve different purposes. Typescript validates types at compile time, whereas PropTypes are checked at runtime. Typescript is useful when you are writing code: it will warn you if you pass an argument of the wrong type to your React components, give you autocomplete for function calls, etc.


1 Answers

This is an es7 version

class App extends React.Component {   static propTypes = {     ...   } } 

while this is the es6 version

class App extends React.Component {   ... }  App.propTypes = {   ... } 

Personally I prefer the es7 version because it makes more sense to view the propTypes at the top of the component, to give an overview of what is needed to render the component (similar to what parameters are needed for a function).

Regardless of which version you are using, if you want to strip propTypes for production, you need to use https://github.com/oliviertassinari/babel-plugin-transform-react-remove-prop-types. Alternatively, you can use https://github.com/thejameskyle/babel-react-optimize which includes the above transform plus a few other goodies since I guess you would also want to optimize your app further (:

like image 176
Yangshun Tay Avatar answered Sep 17 '22 18:09

Yangshun Tay