Common pitfall in initialising state based on props in React JS

Common pitfall in initialising state based on props in React JS  #javascript #tech #hacker

  • Common pitfall in initialising state based on props in React JSRecently I ran into this issue while working on React JS project where I was passing a part of parent component state to child component via props.
  • So the problem was when the parent component re-renders on state change, the child component is not rendered with updated state value.
  • For example —// our child componentclass ChildComponent extends Component { constructor(){ super(props); this.state = { count:this.props.value }; } render(){ return( div pI have {this.state.count} candies!
  • So the state does not update even though child component is re-rendered upon receiving new props form parent component.
  • If you need to update the state in response to prop changes (for example, to reset it), you may compare this.props and nextProps and perform state transitions using this.setState() in this methodnextProps is the latest props received from the parent component.We will use this life cycle method and update the…

Recently I ran into this issue while working on React JS project where I was passing a part of parent component state to child component via props. Then I was using that prop to set the initial state…
Continue reading “Common pitfall in initialising state based on props in React JS”