React - defaultProps vs ES6 default params when destructuring (performances issues)

前端 未结 3 826
遥遥无期
遥遥无期 2020-12-13 00:16

I just came across a question about React performances when settings default values in one of my stateless functional components.

This component had

3条回答
  •  半阙折子戏
    2020-12-13 00:21

    Looking at the advanced use-case you have, you're adding unnecessary properties to the component. label and placeholder are dependent on other properties being passed in and in my opinion, should not be listed as a parameter of the component itself.

    If I were trying to use in my application and I needed to look to see what dependencies that specific component has, I would be a little bit confused as to why you're creating parameters that are based off of other parameters. I would move the label and placeholder into the function's body so it's clear they are not component dependencies but simply side effects.

    As far as performance is concerned here, I'm not sure there would be a significant difference in either way. Stateless components don't really have a 'backing instance' that stateful components do, which means there isn't an in memory object keeping track of the component. I believe it's just a pure function of passing parameters in and returning the view.

    On that same note.. adding the PropTypes will help with the type checking.

    const FormField = ({
      input: { name, value, ...inputRest },
      row = false,
      meta: { touched, error, warning },
      ...others,
    }) => {
      const label = capitalize(name),
      const placeholder = label,
    
      return (
        // logic
      );
    };
    
    FormField.propTypes = {
      input: PropTypes.shape({
        name: PropTypes.string.isRequired,
        value: PropTypes.string,
      }).isRequired,
      meta: PropTypes.shape({
        touched: PropTypes.bool.isRequired,
        error: PropTypes.bool.isRequired,
        warning: PropTypes.bool.isRequired,
      }).isRequired,
      row: PropTypes.bool.isRequired,
    };
    

提交回复
热议问题