Setter function and setState

I have seen the following code:

class Welcome extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      name: ''
    }
  }

  set name(newValue: string) {
    this.setState({ name: newValue });
  }

  get name(): string {
    return this.state.name
  }
}

The setter function puzzles me. Could anyone tell me when the setter function is called? Will it be called by this.setState({ name: ...? If so, will it be infinite?

Similarly for the getter function. Will it be an infinite call?

Answer

Could anyone tell me when the setter function is called?

This is called when attempting to set value to this.name. This is a javascript feature and not related to React.

React ignores all changes to state except when done via setState. Changing name using this.name = 'newName' isn’t normally a valid method of modifying state. All state changes will HAVE to occur via setState. In this code, a custom setter method is defined so that this.name = 'newName' calls this.setState.

There is no conflict in this case. Calling setter method during assignment is javascript feature, React plays no role in it. The setter method modifies the state using setState which then notifies react of the change.

The getter function is called every time you try to access this.name. Since the getter function returns this.state.name, it is as-if this.name expands to this.state.name.