Setter function and setState

I have seen the following code:

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

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

  get name(): string {

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?


Could anyone tell me when the setter function is called?

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

React ignores all changes to state except when done via setState. Changing name using = '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 = '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 Since the getter function returns, it is as-if expands to