DEV Community

Martin Soderlund Ek
Martin Soderlund Ek

Posted on

React Hooks and API Call Sample App

Last time around I wrote about a React sample app with an API call to RandomUser.me.

That version was classic React and now I've updated it to use hooks instead.

With classic React, we used Class components and mutated their internal state via setState when we wanted to do something.

With React hooks, we can use functional components instead, with the State hook useState, which itself is a React function.

We will import useState like this at the top of our file:

import React, { useState } from "react";

Then we'll declare our functional component, like this:

export default function RandomUser() {}

Then we will use EcmaScript 6 (ES6) destructuring and useState to return an array for use in our component:

const [name, setName] = useState([]);

The user and setUser variable names can be anything you want, as long as they are descriptive, of course.

Then we'll use the Effect hook useEffect to initialize our function and insert it into the tree. useEffect "serves the same purpose as componentDidMount, componentDidUpdate, and componentWillUnmount in React classes, but unified into a single API". (React Hooks documentation)

Sweet - useEffect takes care of a lot for us!

As you can see, we have a call to fetchRandomUser(), which will be an async function with our API call.

The complete code looks like this:

Compare this functional component with hooks sample, to the previous class components sample, we now have 48 rows, vs 65 rows before.

Here's the Github repo

Top comments (0)