When to use React "componentDidUpdate" method?

when to use react reddit
when to use react js vs angular
react tutorial
react native
create react app
react vs angular
when to use angular

I wrote dozens of React files, never use componentDidUpdate method.

Is there any typical example of when need to use this method?

I want some real-world example, not a simple demo.

Thanks for the answer!

A simple example would be an app that collects input data from the user and then uses Ajax to upload said data to a database. Here's a simplified example (haven't run it - may have syntax errors):

export default class Task extends React.Component {

  constructor(props, context) {
    super(props, context);
    this.state = {
      name: "",
      age: "",
      country: ""

  componentDidUpdate() {

  _changeName = (e) => {
    this.setState({name: e.target.value});

  _changeAge = (e) => {
    this.setState({age: e.target.value});

  _changeCountry = (e) => {
    this.setState({country: e.target.value});

  _commitAutoSave = () => {
    Ajax.postJSON('/someAPI/json/autosave', {
      name: this.state.name,
      age: this.state.age,
      country: this.state.country

  render() {
    let {name, age, country} = this.state;
    return (
        <input type="text" value={name} onChange={this._changeName} />
        <input type="text" value={age} onChange={this._changeAge} />
        <input type="text" value={country} onChange={this._changeCountry} />

So whenever the component has a state change it will autosave the data. There are other ways to implement it too. The componentDidUpdate is particularly useful when an operation needs to happen after the DOM is updated and the update queue is emptied. It's probably most useful on complex renders and state or DOM changes or when you need something to be the absolutely last thing to be executed.

The example above is rather simple though, but probably proves the point. An improvement could be to limit the amount of times the autosave can execute (e.g max every 10 seconds) because right now it will run on every key-stroke.

I made a demo on this fiddle as well to demonstrate.

For more info, refer to the official docs:

componentDidUpdate() is invoked immediately after updating occurs. This method is not called for the initial render.

Use this as an opportunity to operate on the DOM when the component has been updated. This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed).

When Does a Project Need React?, I'm just going to use React as a placeholder here for kinda large JavaScript framework thingies. Vue, Ember, Svelte… whatever. I understand  We’ll get to the funny XML-like tags soon. We use components to tell React what we want to see on the screen. When our data changes, React will efficiently update and re-render our components. Here, ShoppingList is a React component class, or React component type.

Sometimes you might add a state value from props in constructor or componentDidMount, you might need to call setState when the props changed but the component has already mounted so componentDidMount will not execute and neither will constructor; in this particular case, you can use componentDidUpdate since the props have changed, you can call setState in componentDidUpdate with new props.

When to use REACT and when NOT to use REACT, TO CREATE new COMPONENTS: REACT is basically using an Object.create feature of the prototype model of javaScript modular programming… so the parent-  React allows you to interface with other libraries and frameworks. This example uses remarkable, an external Markdown library, to convert the <textarea>’s value in real time.

I have used componentDidUpdate() in highchart.

Here is a simple example of this component.

import React, { PropTypes, Component } from 'react';
window.Highcharts = require('highcharts');

export default class Chartline extends React.Component {
  constructor(props) {
    this.state = {
      chart: ''

  public componentDidUpdate() {
    // console.log(this.props.candidate, 'this.props.candidate')
    if (this.props.category) {
      const category = this.props.category ? this.props.category : {};
      console.log('category', category);
      window.Highcharts.chart('jobcontainer_' + category._id, {
        title: {
          text: ''
        plotOptions: {
          series: {
            cursor: 'pointer'
        chart: {
          defaultSeriesType: 'spline'
        xAxis: {
          // categories: candidate.dateArr,
          categories: ['Day1', 'Day2', 'Day3', 'Day4', 'Day5', 'Day6', 'Day7'],
          showEmpty: true
        labels: {
          style: {
            color: 'white',
            fontSize: '25px',
            fontFamily: 'SF UI Text'
        series: [
            name: 'Low',
            color: '#9B260A',
            data: category.lowcount
            name: 'High',
            color: '#0E5AAB',
            data: category.highcount
            name: 'Average',
            color: '#12B499',
            data: category.averagecount
  public render() {
    const category = this.props.category ? this.props.category : {};
    console.log('render category', category);
    return <div id={'jobcontainer_' + category._id} style={{ maxWidth: '400px', height: '180px' }} />;

What and Why React.js, if your team: Has frontend designers that are familiar with HTML and aren't comfortable with JSX. Has frontend designers that are familiar with CSS. Facebook has created a Create React Application with everything you need to build a React app. It is a a development server that uses Webpack to compile React, JSX, and ES6, auto-prefix CSS files. The Create React App uses ESLint to test and warn about mistakes in the code. To create a Create React App run the following code on your terminal:


    if (this.state.authToken==null&&prevProps.authToken==null) {
      .then(token => {
        if (token) {
          AccountKit.getCurrentAccount().then(account => {
              authToken: token,
              loggedAccount: account
        } else {
          console.log("No user account logged");
      .catch(e => console.log("Failed to get current access token", e));


React Popularity and When Not to Use React ― Scotch.io, architecture goes with Typescript for web development which is more compact and error-free. React has been designed from the start for gradual adoption, and you can use as little or as much React as you need. Perhaps you only want to add some “sprinkles of interactivity” to an existing page. React components are a great way to do that. The majority of websites aren’t, and don’t need to be, single-page apps.

This lifecycle method is invoked as soon as the updating happens. The most common use case for the componentDidUpdate() method is updating the DOM in response to prop or state changes.

You can call setState() in this lifecycle, but keep in mind that you will need to wrap it in a condition to check for state or prop changes from previous state. Incorrect usage of setState() can lead to an infinite loop. Take a look at the example below that shows a typical usage example of this lifecycle method.

componentDidUpdate(prevProps) {
 //Typical usage, don't forget to compare the props
 if (this.props.userName !== prevProps.userName) {

Notice in the above example that we are comparing the current props to the previous props. This is to check if there has been a change in props from what it currently is. In this case, there won’t be a need to make the API call if the props did not change.

For more info, refer to the official docs:

Why is React important for UI developers? Is it necessary to learn , Use the same techniques for deciding if you should create a new function or to your underlying data model and call ReactDOM.render() again, the UI will be  Styling React Using CSS Previous Next There are many ways to style React with CSS, this tutorial will take a closer look at inline styling , and CSS stylesheet .

React vs Angular: What to Choose for Your App?, to variables declared within a function). Here are some good resources for further reading on when to use props vs state : Props vs State · ReactJS: Props vs​. It’s relatively easy to replace React due to PureScript’s react and react-basic libraries. The React mental model fits well with a strongly-typed, pure functional language like PureScript (or Reason), and using the same underlying library means that components can be shared between languages with little modification.

Thinking in React – React, Component { render() { // Use a Provider to pass the current theme to the tree below. // Any component can read it,  When React renders a component that subscribes to this Context object it will read the current context value from the closest matching Provider above it in the tree. The defaultValue argument is only used when a component does not have a matching Provider above it in the tree.

Component State – React, Why use ReactJS? What is it in the first place? While often considered a JavaScript framework like Angular or Vue.js, React is actually a frontend  Learn how to build and launch React web applications using React, Redux, Webpack, React-Router, and more! 4.7 (16,134 ratings) Course Ratings are calculated from individual students’ ratings and a variety of other signals, like age of rating and reliability, to ensure that they reflect course quality fairly and accurately.

  • developmentarc.gitbooks.io/react-indepth/content/life_cycle/…
  • A simple case when you wish to set initial state of component on load.
  • @Rajesh Can you explain it or give me a example? Thanks!
  • I think the most common use-case is when you have other libraries (jQuery, D3...) that work directly on the DOM, coupled together with React. In such scenarios, if the other library needs to perform DOM transformations, you should use componentDidUpdate to ensure React's shadow DOM has been flushed to the real DOM.
  • To elaborate on @Jorge's comment: I think the most common case would be to READ from the real DOM after React has updated. E.g. when you want to know the exact dimensions of DOM elements, or the position of DOM elements in the viewport. E.g. for animations or transitions you want react to manage. I would definitely advise against using jQuery for changing the DOM after react has rendered. Having react + another library change the same piece of DOM is a bad idea.
  • I think this.setState({...}, callback), the callback equal _commitAutoSave, what do you think? So, I think this case can use componentDidUpdate method, but not must, am i right? fiddle
  • Yes, you could use a callback, however the problem gets trickier when/if there are multiple setStates that are run in succession.
  • Thanks for your answer. So, one case to use componentDidUpdate is to solve multiple setStates! Any other ideas?
  • @novaline I see they use it in the react-sound component github.com/leoasis/react-sound/blob/master/src/index.js .. I'm not exactly sure why they're using it but I thought I'd share the link for you to take a look.
  • This is a good example, but it's missing a key recommendation from the React docs. "This is also a good place to do network requests as long as you compare the current props to previous props (e.g. a network request may not be necessary if the props have not changed)." reactjs.org/docs/react-component.html#componentdidupdate Similarly, one should wrap the call in conditional logic whenever calling setState in CDU.
  • What to do in case of this.fetchData is not a function?
  • tomrlh it's a function call