State Reset and Update with React
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!




A safety check if the value returned is
undefinedspread operators break, if we try to spreadundefinedvalueThanks 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 });Would it be better to have
defaultStatevariable defined as a const outside the class? Then you’re sure it won’t get changed by mistake.