1

How should I reset the state of a Child on every prop change?

Parent component:

render() {
    const { show, month } = this.props; // January, February, ...

    return (
      { show ? <Child selectedMonth={month} /> : null }
    );
  }

Child component:

componentDidMount() {
    this.resetChildState();
    // this will never run if the Parent's month prop is changed
    // only if show becomes false from true
  }

I want resetChildState to run on every month change.

vrotos
  • 33
  • 1
  • 11

4 Answers4

3

Just try to use componentDidUpdate, in the body of this method you can compare whether props from parent changed or not. So if they did just call your reset method or whatever you want. For more info visit https://reactjs.org/docs/react-component.html#componentdidupdate

componentDidUpdate(prevProps, prevState) {
   if(this.props.selectedMonth!== prevProps.selectedMonth) {
        this.resetChildState();
   }
}
Roman Unt
  • 893
  • 7
  • 8
1

You can use getDerivedStateFromProps()

static getDerivedStateFromProps(nextProps, prevState) {
 if(monthChanged){
  return initialState; //reset to initialState that you have defined.
  }
 return null;
}
1

if you want just reset your state exactly after changing the props, you can use the componentWillReceiveProps react lifecycle as below:

class Children extends React.Component {
    // ...
    state = {
      name: "test"
    };

    componentWillReceiveProps(nextProps) {
      this.setState({name: ""});
    }
    // ...
}
Ali Torki
  • 1,929
  • 16
  • 26
0

use ComponentDidUpdate

 componentDidUpdate() {
        if (this.props.id !== this.state.section_id) {
            this.setState({
                section_id:this.props.id,
                filteredProducts:[],
                productsByPage:[],
                pageNumber:0,
                hasMore:true,
                showloading:true

            },()=>this.fetchData());
        }
    }