Reputation: 5127
I'm still learning React and can't grasp the importance of PropTypes
. Can anyone give their thoughts what are the benefits of defining your PropTypes
? I've read the discussion about this on the React documentation but I can't grasp the advantages of keeping PropTypes
aside from seeing console error/warnings when types doesn't match. It says on the documentation
When designing interfaces, break down the common design elements (buttons, form fields, layout components, etc.) into reusable components with well-defined interfaces. That way, the next time you need to build some UI, you can write much less code. This means faster development time, fewer bugs, and fewer bytes down the wire.
So aside from the benefits I have a few other questions:
PropTypes
you are definitely writing more code which contradicts that statement in bold.PropTypes
only applicable to child components since parent components don't usually have props?StateTypes
so to speak?Upvotes: 28
Views: 6592
Reputation: 16754
PropTypes
let you validate your props, which otherwise is not possible, since JavaScript is loosely typed language.
You can have props
wherever you need them, including parents. Or do not have them at all. Often props
are the only way to pass some values or callbacks from parents to children and grandchildren (in fact it is recommended way).
There's no StateTypes.
Upvotes: 1
Reputation: 19133
React revolves around the concept of components. A whole webpage should be broken down into components and each components will interact with each other through props
.
So, these are all the advantages of using PropTypes
PropTypes
PropTypes
is not compulsory.
[EDIT] Answers for the questions in order
props
, which is extra code, you don't need to do it by yourself. Validations will be taken care by React
itself.Parent
and Root
component. Parent
component can be a child of another Parent
which can be a child of another. So, call it as Root
component which will be at the top of the UI tree. With this definition, you can say, PropType
is only applicable to Parent
and Child
, not Root
component.stateType
because state
is with in a component's scope. But, props
are passed from a component to another. So, it doesn't make sense to validate state
of a component as it is not shared across components. Even if it is shared, that can be only done through props
.Hope it helps...
Upvotes: 32