react componentDidUpdate code example

Example 1: component did update arguments

componentDidUpdate(prevProps, prevState) {
  // only update chart if the data has changed
  if (prevProps.data !== this.props.data) {
    this.chart = c3.load({
      data: this.props.data
    });
  }
}

Example 2: componentDidUpdate

componentDidUpdate(prevProps, prevState) {
  if (prevState.pokemons !== this.state.pokemons) {
    console.log('pokemons state has changed.')
  }
}

Example 3: componentdidupdate in hooks

const App = props => {
  const didMountRef = useRef(false)
  useEffect(() => {
    if (didMountRef.current) {
      doStuff()
    } else didMountRef.current = true
  }
}

Example 4: prev props

componentDidUpdate(prevProps) {
  // Utilisation classique (pensez bien à comparer les props) :
  if (this.props.userID !== prevProps.userID) {
    this.fetchData(this.props.userID);
  }
}

Example 5: shouldcomponentupdate

shouldComponentUpdate(nextProps, nextState) {
  return true;
}

Example 6: component did mmount

componentDidMount()