Fetching Data with async/await in a React Component

Fetching data from a resource, such as a JSON API is a common thing these days, and so is the use of asynchronous (async) functions that avoid locking up applications.

In React components, async functions have some additional caveats to keep in mind that –if left unchecked– can introduce memory leaks or race conditions.

In this article, we’ll be covering a small app that fetches articles from an API and lists them out. We’ll take a look at async functions in a React component, address caveats, and checkout making our function reusable as a custom React hook.

This article will cover:
đź’š Async/Await use in a React component
đź’š Writing cleaner code with custom hooks
💚 Testing async/await in Jest 👩‍🔬

âś” Familiar with functional React component basics
âś” Basic understanding of async/await

An Introduction to React

I’ve been working with React a bit lately and wanted to document my experience and findings. Since there’s quite a few “hello world”/getting started guides out there already, I’ll provide links to those and cover key points I took away from articles and experience.

When React was announced around mid-2013, it looked like an interesting concept and seemed like it should be pretty significant considering it was being maintained by Facebook. However, it fell off my radar soon after. as It was too early to use in any of my projects. Looking at where React stands now in addition to supporting libraries, I can see  that the scene has matured and stabilized quite a bit.

What is React?

React is a JavaScript library created by Facebook that fulfills the functionality of the view in MV*C. It stands by itself and aligns with the “single responsibility” principle that is the first of the five S.O.L.I.D object-oriented programming and design principles. Other concerns such as routing, controller, and model/stores are separate patterns that exist outside of React.

Because of this separation, React can fit into other frameworks or be pieced together with other libraries to make a complete MV*C framework, such as Flux (see which Flux implementation should I use on history/development of Flux), Redux, or Cerebral.

React is designed to be scalable and fast. Some patterns like its root level event listener are intended to make React fast, and other features, such as the virtual DOM, use encapsulation to reduce or eliminate common problems with scaled web applications caused by conflicting class/ID names and DOM manipulation side effects.

Also worth noting, React was split into react-dom and  react-native to independently support browser and mobile apps. For this article, I’ll be covering what is referred to as react-dom, which is React for the browser.

Learning Curve

Working with React and its ecosystem has been interesting. Given you’re already familiar with JavaScript, React itself isn’t that difficult to comprehend. Though it does take some time to understand the concepts React is founded on and what problems it is addressing. For example, the data flow design may take some time to get used to.

The challenges with React more lie in the ecosystem, when third-party libraries and the build process come into play. However, the libraries are worth getting familiar with, and the build process should become less confusing as things settle down. For now, there are plenty of boilerplate start projects on github.

Getting Started

The first step is to take it easy and not get overwhelmed. There are a collection of technologies that make a React stack, and they don’t have to be learned at once, I recommend first focusing on React and JSX first. By understanding the core concepts and working with plain React is a good start.

React’s homepage goes over the fundamentals of building a React app from scratch without diving too far into the tool chain. A starter kit can be downloaded from their getting started guide.

Most examples require compiling the HTML like markup called JSX into JavaScript. This can be done through a browser version of the Babel library called Babel Standalone. However I’ve found this makes debugging difficult, because I can’t set accurate breakpoints. Compiling the application outside of the browser as part of the build process is recommended.

The following is a simple “Hello World” component defined with a pure function. For components that don’t hold state (covered further down), pure functions are preferred over react factories, such as React.createClass or React.createComponent.

See the Pen React Hello World by Justin Osterholt (@hattraz) on CodePen.0

Shorthand Javascript Techniques

(This is for coders familiar with the JavaScript language. Information on more basic JavaScript usage can be found at sites like w3schools.com.)


Keeping code standardized can be made easier through JavaScript shorthand. Here we will be looking at several techniques that will make code more readable, flexible and overall easier to matain.

Mathematic Operations
Anonymous Functions



Instead of declaring each variable individually, they can be placed on the same line with a comma separating them.

var foo1, foo2, foo3, foo4;


var foo_arr = ['bar1',  'bar2',  'bar3', ' bar4'];
window.alert(foo_arr[0]); //bar1


var foo_obj = {name:  'bar', some_prop: 'test'};
window.alert(foo_obj.name); //bar


condition? true_logic :  false_logic;

Shorthand conditional statements can be coupled with an assignment, allowing  a single line of code to be used for simple conditional logic.

var foo = bar? 1 : 0;

Assigning a default value when encountering an empty variable (null, undefined, 0, false, empty string) can also be shortened from this

if(foo) {
    bar = foo;
} else {
    bar = 'Default Value';

to this

bar = foo || 'Default Value';

Mathematic Operations

Handling math operations can be shorted by using the following syntax:

foo = 5;

foo ++; // Increase by one

foo --; //Decrease by one

foo -= 2; //Decrease by two

foo += 2; //Increase by two

foo *= 3; //Multiply by three

foo /= 2; //Divide by two

Anonymous Functions

Assigning a function to a variable:

var my_func = function() { alert('Hello World') }

Inline anonymous functions:

var foo = {
    name: 'bar',
    fnc:  function() {
        alert('Hello World');

Common Usage

Combining the use of shorthand results in blocks of code that appear more elegant and easier to read.

var foo = [
    {name: 'apple', prop2: 'test2'},
    {name: 'orange', prop2: 'test2'}

Instead of:

function fruit(type, cultivar)
    this.type= type;
    this.cultivar = cultivar;
var foo = Array(
    new fruit('Apple', 'Fuji'),
    new fruit('Apple', 'Gala')

As you can see, using shorthand removes “noise” and reduces the amount of written code, both of which make for easier reading. When rummaging through scripts that contain several hundred lines of code, removing any excess code makes life easier.