Home > Enterprise >  Should I use the package prop-types or pass a Props interface to React components?
Should I use the package prop-types or pass a Props interface to React components?

Time:10-05

I have been working in a react typescript project for awhile and the way that we had been type-checking props was with the React.FC generic. Going into the react typescript documentation I find code like the following:

interface DateProps {
  iso8601Date: string;
  message: string;
}

const DateComponent: FauxactFunctionComponent<DateProps> = props => (
  <time dateTime={props.iso8601Date}>{props.message}</time>
);

However I just started a new project and there have been a few updates and we updated the eslint to the recommended for react. The new eslint rules are throwing the error:

 "missing in props validation eslintreact/prop-types"

This can easily be avoided by following changing some linting rules recommended here:

"rules": {
  "react/prop-types": "off"
}

I am tempted to turn off this linting rule and do it as we have done in the past. I don't think I see any added benefit from the docs. But am asking if there is something I am missing with the use of prop-types and why might it be better than the original method? I am leaning towards turning it off.

CodePudding user response:

React PropTypes is a runtime check: in case of incorrect types / missing/extra props, you would get a runtime error in the browser console pointing out the discrepancy (besides possibly a crashing component in case of missing prop...).

It is useful when there is no static type check in the project, as described in the documentation:

For some applications, you can use JavaScript extensions like Flow or TypeScript to typecheck your whole application. But even if you don’t use those, React has some built-in typechecking abilities.

In your case, you use TypeScript for static type check of the props, it is very good at this job in almost every situation (minus very acute corner cases).

Besides, the main IDE's (in particular VS Code) have TSX support that leverage your prop type definition to validate them within the JSX syntax, as if it were a normal function call.

PropTypes also enables specifying default prop values; it is the main way to do so in class-based components. But with Function components, we can simply use JS default parameters (even when destructuring).

Therefore, in line with the docs, if you properly specify the TS types on your props, and use only Function components, there is need to double the work with React PropTypes, and you can safely disable this linter rule.

  • Related