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
    Responsive and Infinitely Scalable JS Animations

    Back in late 2012 it was not easy to find open source projects using requestAnimationFrame() - this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...

  • By
    Vibration API

    Many of the new APIs provided to us by browser vendors are more targeted toward the mobile user than the desktop user.  One of those simple APIs the Vibration API.  The Vibration API allows developers to direct the device, using JavaScript, to vibrate in...

Incredible Demos

  • By
    Google Font API

    Google recently debuted a new web service called the Font API.  Google's Font API provides developers a means by which they may quickly and painlessly add custom fonts to their website.  Let's take a quick look at the ways by which the Google Font...

  • By
    Introducing LazyLoad 2.0

    While improvements in browsers means more cool APIs for us to play with, it also means we need to maintain existing code.  With Firefox 4's release came news that my MooTools LazyLoad plugin was not intercepting image loading -- the images were loading regardless of...

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!