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
    Being a Dev Dad

    I get asked loads of questions every day but I'm always surprised that they're rarely questions about code or even tech -- many of the questions I get are more about non-dev stuff like what my office is like, what software I use, and oftentimes...

  • By
    CSS vs. JS Animation: Which is Faster?

    How is it possible that JavaScript-based animation has secretly always been as fast — or faster — than CSS transitions? And, how is it possible that Adobe and Google consistently release media-rich mobile sites that rival the performance of native apps? This article serves as a point-by-point...

Incredible Demos

  • By
    Image Manipulation with PHP and the GD Library

    Yeah, I'm a Photoshop wizard. I rock the selection tool. I crop like a farmer. I dominate the bucket tool. Hell, I even went as far as wielding the wizard wand selection tool once. ...OK I'm rubbish when it comes to Photoshop.

  • By
    Introducing MooTools HeatMap

    It's often interesting to think about where on a given element, whether it be the page, an image, or a static DIV, your users are clicking.  With that curiosity in mind, I've created HeatMap: a MooTools class that allows you to detect, load, save, and...

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!