Croft70
Croft70

Reputation: 43

Calling setstate on a parent component forces componentDidUpdate on its children?

I have two components, parent component App and child component SearchBar, I want SearchBar to keep its own state, and after updating its state to call a function given by its parent as a prop that will update its parent state.

So on my SearchBar component I have

onSearchChange(event) {
        .
        .
        .
        this.setState({ searchTerm });

    }

And then

componentDidUpdate(){
    this.props.onSearchChange(this.state.searchTerm)
}

And on the parent component

onSearchChange(searchTerm){
    this.setState({searchTerm});
}
render() {
    return (
        <div className="App">

            <div>
                <SearchBar onSearchChange={this.onSearchChange}/>
            </div>
            .
            .
            .
        </div>
    );
}

But this causes an infinite loop where SearchBar's componentDidUpdate gets called which calls its parent onSearchChange to update the parent state but then SearchBar's componentDidUpdate its called again an so on.

If I use a callback in setState instead of componentDidUpdate to update its parent state it works correctly, but I just don't understand why SearchBar its updating if its prop its constant.

Upvotes: 4

Views: 1584

Answers (1)

Giorgi_Mdivani
Giorgi_Mdivani

Reputation: 383

componentDidUpdate provides two arguments prevProps and prevState, with it you can check if actual props or state has changed and then make changes to current state/props.. for example:

componentDidUpdate(prevProps, prevState){
if(prevState.searchTerm !== this.state.searchTerm) {
   this.props.onSearchChange(this.state.searchTerm)
  }
}

Upvotes: 6

Related Questions