testinggnitset ser
testinggnitset ser

Reputation: 297

prevent child components from rerendering whem making changes to parent state

So I have a spinner in my child component where whenever the parent component updates its state it rerenders everything including the child, which makes the child component's spinner appear on every change in state from the parent.

Is there a way to prevent this so that the spinner will only appear on certain changes to the parent state?

Upvotes: 1

Views: 1868

Answers (2)

Kamelkent
Kamelkent

Reputation: 329

I'm not really sure what your code looks like but as I see it you have two options:

class MyClass extends React.Component {
  constructor(props) {
    this.state = { showSpinner: true }
  }
  
  componentDidMount() {
    myAsyncFetch.done((data) => {
      this.setState({ showSpinner: false })
    })
  }
  
  render() {
    if (this.state.showSpinner) {
      return <Spinner/>;
    }
    
    return <div/>; // Content
  }
}

Upvotes: 1

Rodius
Rodius

Reputation: 2311

I assume you're passing the parent state as a prop to the child. You can use the ShouldComponentUpdate lifecycle method to prevent the child from re-rendering when the prop coming from the parent doesn't require the child to be updated.

Upvotes: 2

Related Questions