Calling a props function from constructor vs componentDidMount?

Viewed 453

In my react component, there is a function in props that I want to call at the time of component rendering which can be called from either constructor or componentDidMount() function. Mostly I don't see calling function from constructor in general in react project that I saw so far? But in my case, it doesn't matter where I call it (constructor vs componentDidMount(). So, I was thinking to call from constructor just before the component is rendered.

Is there any downside in calling the function from constructor?

Call from constructor looks like below:

export class XYZ extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [],
    };

    this.props.updateId(0);
  }


  .....

  render() {
      ......
  }
}

Call from componentDidMount() looks like below:

export class XYZ extends Component {
  constructor(props) {
    super(props);
    this.state = {
      selectedItems: [],
    };
  }

  componentDidMount() {
    this.props.updateId(0);
  }


  .....

  render() {
      ......
  }
}

Edit: updateId function is defined in parent component where it just pass the Id 0 to parent component and then parent component sets it in state which is used to show something.

1 Answers

If you need to call Parent function before rendering the Child Component then you call it in Constructor, but if you need to call it after Child Component rendered, then You can use componentDidMount method.

Note that, if you gonna switch to react Hooks then it would be useful to call parent functions conditionally or inside useEffect.

Related