Proptypes for custom react hooks

后端 未结 4 823
长情又很酷
长情又很酷 2021-01-04 00:36

With react hooks coming, should we use prop-types for React custom hooks e.g,

import React from \'react\';
import PropTypes from \'prop-types\';    

const u         


        
相关标签:
4条回答
  • 2021-01-04 00:39

    No. React doesn't validate custom hooks or in-built hooks props.

    Look here for updateFunctionComponent, It validates prop types using checkPropTypes for a react component and then render it with hooks i.e. check out renderWithHooks.

    Now if you check here in renderWithHooks method, It updates the dispatcher and calls your functional component which in turn calls your custom hook, since it's just another function call inside your functional component.

    Your custom hook will call in-built hooks. You can check the implementation here . Based on type of dispatcher it will call built-in hooks. If you search checkPropTypes in the whole file you won't find the validation logic or prop-types/checkPropTypes dependency which is used to validate the prop types.

    Here is some nice article about how react hooks works

    0 讨论(0)
  • 2021-01-04 00:48

    Typescript is the best way for validation and check props

    import React from 'react';   
    
    const useTitle = ({title}:{title?:string})=> {
      React.useEffect(() => {
        document.title = title;
      }, [title]);
    }
    
    export default useTitle;
    

    Or

    import React from 'react';   
    
    type customPropType= {
        title?:string
    }
    
    const useTitle = ({title}:customPropType)=> {
      React.useEffect(() => {
        document.title = title;
      }, [title]);
    }
    
    export default useTitle;
    
    0 讨论(0)
  • 2021-01-04 00:50

    I'm using PropTypes.checkPropTypes for useSelector hook. And it works for me.

    const useTitle = title => {
      React.useEffect(() => {
        document.title = withPropsValidation(title);
      }, [title]);
    }
    
    const withPropsValidation = props => {
      PropTypes.checkPropTypes(propTypes, props, 'prop', '')
      return props
    }
    
    const propTypes = {
      title: PropTypes.string.isRequired,
    }
    

    https://github.com/facebook/prop-types#proptypescheckproptypes

    0 讨论(0)
  • 2021-01-04 01:03

    In my opinion, using some kind of type mechanism would be better like TypeScript but if you don't you should still use propTypes and additionally you can check this course out from kentcdodds to be sure about propTypes usage https://egghead.io/courses/simplify-react-apps-with-react-hooks

    0 讨论(0)
提交回复
热议问题