How to use Redux' useSelector and useDispatch hooks with PropTypes
Asked Answered
S

2

6

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.

Summons answered 25/9, 2019 at 20:55 Comment(0)
W
7

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.

Wolfgang answered 14/10, 2019 at 22:51 Comment(0)
R
4

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

Rawalpindi answered 25/8, 2020 at 10:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.