I Love ReactJS

Why did the React team abandon defaultProps in functional components

Why did the React team discard defaultProps ?

in functional components

come to a conclusion first, because it is not necessary.

in functional components, we can declare default properties in the form of JS default parameters, as follows:

function Foo({foo = 1, bar = "hello"}) {
  let props = {foo, bar};
  //...
}

The advantage of this is that React 's defaultProps is a black box for most teams.

if we put the behavior of the default property in the function component definition, it is more controllable from the point of view of code quality.

so what was defaultProps designed for?

React the team thinks defaultProps is very useful in classes.

because props objects are passed to many different methods: life cycle, callback, and so on. Each function has its own context that requires an initial default value. This makes it difficult to implement using the JS default parameter, because you have to copy the same default value in each function. The following is an example:

class Foo {
  static defaultProps = {foo: 1};
  componentDidMount() {
    let foo = this.props.foo;
    console.log(foo);
  }
  componentDidUpdate() {
    let foo = this.props.foo;
    console.log(foo);
  }
  componentWillUnmount() {
    let foo = this.props.foo;
    console.log(foo);
  }
  handleClick = () => {
    let foo = this.props.foo;
    console.log(foo);
  }
  render() {
    let foo = this.props.foo;
    console.log(foo);
    return <div onClick={this.handleClick} />;
  }
}

to sum up, the role of defaultProps is that in class components, new default values can be used in each lifecycle and scope of methods.

therefore, it has been implemented in subsequent updates of the React team: using defaultProps in functional components, React adds a warning to createElement . This includes other special components, such as forwardRef and memo .

Summary

  1. in functional components, you should use JS function default parameters to define component default properties, and avoid using defaultProps .
  2. also consider applicable scenarios when using Api provided by the framework. Think about how to implement code in a simpler and more controllable way when writing code.

reference link

## Deprecate defaultProps on function components

Exit mobile version