In React class components with mapStateToProps, mapDispatchToProps
every incoming state/dispatch prop is easy to type check with PropTypes.
When rewriting mapStateToProps -> useSelector
, and mapDispatchToProps -> useDispatch
I no longer see any logical place to do proptype checking. Unless I manually check proptypes with PropTypes.checkPropTypes()
.
I guess it's more important to do proptype checks of props from parent components than from Redux, but I would still like to know if anyone has a good solution.
When you call connect()
in your component, what you're doing is creating an HOC or Higher Order Component. This component "wraps" in which you call connect()
. The HOC then passes props to the wrapped component as a props
object.
The members of this object can in-turn be type-checked by a package like prop-types
. The problem here is that when using hooks, you're no longer wrapping the component at all. You're deriving state right there in the function body as the function runs. This means that the value you are using is no longer a "prop".
Unfortunately, there is no convenient way to automatically type-check values in JavaScript. One could add TypeScript or Flow, but that brings type-checking for every variable/function return in the entire file. Perhaps this is what you want, but it adds a great deal of overhead.
I'm using PropTypes.checkPropTypes for useSelector hook. And it works for me.
const { title, loggedIn } = withPropsValidation(
useSelector(state => ({
title: state.title,
loggedIn: state.loggedIn
})))
const withPropsValidation = props => {
PropTypes.checkPropTypes(propTypes, props, 'prop', '')
return props
}
const propTypes = {
title: PropTypes.string.isRequired,
loggedIn: PropTypes.bool.isRequired,
}
https://github.com/facebook/prop-types#proptypescheckproptypes
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With