React.js
Angular
Ethical Hacking
Agile
AWS
BlockChain
Cassandra
Cloud
Salesforce
Scaled Agile
TOGAF
DevOps
GIT
Jenkins
Jira
Kibana
Linux
NGINX
Ansible
Artificial Intelligence
in React JS by

What will happen if you use props in initial state?

Click here to read more about DevOps

1 Answer

0 votes
by

f the props on the component are changed without the component being refreshed, the new prop value will never be displayed because the constructor function will never update the current state of the component. The initialization of state from props only runs when the component is first created.

The below component won't display the updated input value:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      records: [],
      inputValue: this.props.inputValue
    };
  }

  render() {
    return <div>{this.state.inputValue}</div>
  }
}

Using props inside render method will update the value:

class MyComponent extends React.Component {
  constructor(props) {
    super(props)

    this.state = {
      record: []
    }
  }

  render() {
    return <div>{this.props.inputValue}</div>
  }
}

Related questions

Madanswer
0 votes
asked Jul 2, 2019 in React JS by Venkatshastri
0 votes
asked Jun 19 in React JS by JackTerrance
...