Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use Redux' useSelector and useDispatch hooks with PropTypes

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.

like image 504
Michael Johansen Avatar asked Sep 25 '19 20:09

Michael Johansen


2 Answers

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.

like image 96
Jim Wharton Avatar answered Oct 19 '22 06:10

Jim Wharton


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

like image 4
J_Bon Avatar answered Oct 19 '22 06:10

J_Bon