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

Incredible Demos

  • By
    Animated AJAX Record Deletion Using Dojo

    I'm a huge fan of WordPress' method of individual article deletion. You click the delete link, the menu item animates red, and the item disappears. Here's how to achieve that functionality with Dojo JavaScript. The PHP - Content & Header The following snippet goes at the...

  • By
    The Simple Intro to SVG Animation

    This article serves as a first step toward mastering SVG element animation. Included within are links to key resources for diving deeper, so bookmark this page and refer back to it throughout your journey toward SVG mastery. An SVG element is a special type of DOM element...

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!