ComponentDidUpdate And PrevState
Here's the scenario. I have a parent component, with a child component. Parent component does the ajax calls and pushes data down to the child.
When child component receives new data, within componentDidUpdate (of the child) i will re-set its internal state.
componentDidUpdate(prevProps, prevState) {
if ( prevProps.myRow !== this.props.myRow ) { //check for when new data is passed into this component from its parent / container...
this.setState({
editableRowObj : this.props.myRow //... only then I should bother updating the state with the new data passed in.
})
}
}
I cannot think of a scenario where inside componentDidUpdate (of the child) I will need to check
prevState !== this.state
This is because when I pass new data into the child component, this.state will be equal to prevState (which will be the old state, prior to receiving new data); i.e. until such time as I run the above setState, the prev and current states will remain the same.
Hence my question is, under what scenarios will I need to check prevState != this.state ?
Answer
The same scenario that applies to props, can apply to props. It might so happen that on change of state you need to trigger an API call to fetch the data. Now you might decide to call a function in the setState
callback, but if the same state is being changed from multiple places then componentDidUpdate
is a good place.
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?