Not using PropTypes in your React application ? Start using them to improve the developer experience and make your colleague’s life simpler. 🙂
PropTypes is a package that does runtime checking of props and also you can use them to document the
typeof and required props to your react component.
Sometimes, people may do a mistake in passing the right props to your component.
- They may either miss out passing the required props.
- Or they may pass a prop of a different type.
These issues can be handled well by using PropTypes.
For example, check out below code snippet :
Here, we are passing prop
firstName with the boolean value
true and not passing
WelcomeUser component is expecting
lastName prop of type
This kind of error will not be thrown to the developer.
If the component is expecting many props, it will be hard for the developer to figure out what kind of props these are.
To solve this problem, we can define
PropTypes to our
Any developer can just go through the
WelcomeUser component and easily understand what all are required props, optional props and the data type of props.
If there is something wrong with the props, it will throw the error in the console during runtime.
You can define
PropTypes similar way to
class based components as well.