State Reset and Update with React

By  on  

If you follow me on Twitter, you'll know that I've taken a real liking to React, as has seemingly everyone else in the JavaScript development world.  The React app I'm working on is relatively small, making fetch requests to send and receive data, rendering only one set of data, so I'm doing a lot of resetting of component state  along with a small state modification depending on the result of the AJAX request.  Let's have a look at how I do it!

The JavaScript

There's not much to the state object -- just a few properties:

class Controller extends React.Component {

  // Added as a component property
  defaultState = { data: null, error: null };

  constructor(props) {
    super(props);

    // Set the default state immediately
    this.state = this.defaultState;
  }

  // ....
}

You can probably gather that either data or error will have data, the other will be null, thus I'm essentially resetting the original state value and then populating data or error.  To do this I've created a resetStateWithUpdates method that looks as follows:

resetStateWithUpdates(stateUpdates = {}) {
  // Rest operators ensure a new object with merged properties and values.
  // Requires the "transform-object-rest-spread" Babel plugin
  this.setState({ ...this.defaultState, ...stateUpdates });
}

And is used like:

// Ooops, fetch error!
// `data` implicitly reset to null
this.resetStateWithUpdates({
  error: 'Fetching data failed!  Please try again!',
});

// ... or we got good data!
// `error` implicitly reset to null
this.resetStateWithUpdates({ data });

Using the spread operator to merge the default state and updated state information saves multiple renders from multiple setState calls.  The code is also very short!

Everyone has their own way to handle state within their React apps, so I'm not asserting this is the best method for resetting state with a small update, but it works wonderfully for me.  The code is short, descriptive, and reusable!

Recent Features

  • By
    9 Mind-Blowing Canvas Demos

    The <canvas> element has been a revelation for the visual experts among our ranks.  Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead.  Here are nine unbelievable canvas demos that...

  • By
    CSS 3D Folding Animation

    Google Plus provides loads of inspiration for front-end developers, especially when it comes to the CSS and JavaScript wonders they create. Last year I duplicated their incredible PhotoStack effect with both MooTools and pure CSS; this time I'm going to duplicate...

Incredible Demos

Discussion

  1. Anup

    A safety check if the value returned is undefined spread operators break, if we try to spread undefined value

  2. Thanks for the post David! Like the use of the spread operator for updating state. You can even make the call to it one step smaller with shorthand properties:

    this.resetStateWithUpdates({
      data
    });
    
  3. Tomasz

    Would it be better to have defaultState variable defined as a const outside the class? Then you’re sure it won’t get changed by mistake.

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!