React Pattern: Centralized PropTypes

Avoid repeating yourself by centralizing PropTypes

Grand Central Station, New York, NY

There are three popular ways to handle types in React: PropTypes, TypeScript and Flow. This post is about PropTypes, which are currently the most popular.

Since PropTypes provide type warnings at runtime, it’s helpful to be as specific as possible.

  • Component accepts an object? Declare the object’s shape.
  • Prop only accepts a specific list of values? Use oneOf.
  • Array should contain numbers? Use arrayOf.
  • You can even declare your own types. AirBnB offers many additional PropTypes.
  • In real apps with large objects, this quickly leads to a lot of code. That’s a problem, because in React, you’ll often pass the same object to multiple components. Repeating these details in multiple component files breaks the DRY principle (don’t repeat yourself). Repeating yourself creates a maintenance problem.

    The solution? Centralize your PropTypes.

    Read on at Medium.com

Subscribe to Email Updates (No spam. Just new posts.)

Comments are closed.