score:10

Accepted answer

It is because your Child component is using its own state as well. Always ask yourself if state is necessary, its a common mistake for React beginner.

Hope you can understand it more by looking at this example. Instead of calling setInterval in your constructor function, I will recommend you to call it in componentDidMount and to clearInterval in your componentWillUnmount.

// Since you are not using state, you can use functional component for your Child component
const Child = ({ number }) => <h1>{number}</h1>;

class Parent extends React.Component {
  constructor(props) {
    super(props);
    this.timer = null;
    this.state = { number: 0 };
  }

  componentDidMount() {
    // setInterval after component did mount
    this.timer = setInterval(this.incrementNumber, 1000);
  }

  componentWillUnmount() {
    // clearInterval when component is going to unmount
    if (this.timer) {
      clearInterval(this.timer);
    }
  }

  incrementNumber = () => {
    // setState function callback to ensure state received will be latest state
    this.setState(prevState => ({ number: prevState.number + 1 }));
  }

  render() {
    const { number } = this.state;
    return (
      <div>
        <Child number={number} />
      </div>
    );
  }
}

score:1

your approach is wrong dont update you parent state from child like this and don't save props in child state they are already updated as the parent updates.

and if you want to update parent form child pass props form child to parent like this.when parent updates child will update too.

class Child extends Component {
  constructor(props) {
    super(props);
  }

updateNumber=()=>{// update parent form child. call this function in somewhere in your component. if you want to pass event pass it as second argument
  this.props.updateNumber(newUpdatedNumber,event);
}

  render() {
    return (<h1>{this.props.number}</h1>);
  }
}

class Parent extends Component {

  constructor(props) {
    super(props);
    this.state = {
      number: -1,
    };
    this.child = React.createRef();
    setInterval(this.updateState.bind(this), 1000);
  }

  updateState() {
    console.log(this.state);
    this.setState({
      number: Math.floor((Math.random() * 10) + 1),
    });
  }
//update parent from child

  updateParentFromChild=(updatedNumber,event)=>{//catch function from child 
   this.setState({
      number:updatedNumber
   });
  }


  render() {
    return (
      <div>
        <Child ref={this.child} updateNumber={this.updateParentFromChild} number={this.state.number}/>
      </div>
    );
  }
}

score:11

One easy option to re-render a child is to update a unique key attribute every time you need a re-render.

<ChildComponent key={this.state.updatedKey}/>


Related Query

More Query from same tag