How to Fetch Data with React Hooks in a Minute

Connor Wilson
2 min readNov 21, 2018

--

These are some hooks. Photo by Brook Anderson on Unsplash

Update Feb. 6, 2019: I’ve updated this now that Hooks are officially out! Let me know how you like them on Twitter.

React Hooks are an exciting new feature that let you do things in function components instead of using classes, like fetch data. There’s a lot of discussion around them, but you’re here to fetch data!

Fire up a new create-react-app with npx create-react-app hooks-test. Now that Hooks have been officially released, this is the only step you need!

Create a component in /src/ called Photos.js and give it a basic list:

// Photos.js
import React from "react";
import { useFetch } from "./hooks";
function Photos() {
const [data, loading] = useFetch(
"https://jsonplaceholder.typicode.com/photos?albumId=1"
);
return (
<>
<h1>Photos</h1>
{loading ? (
"Loading..."
) : (
<ul>
{data.map(({ id, title, url }) => (
<li key={`photo-${id}`}>
<img alt={title} src={url} />
</li>
))}
</ul>
)}
</>
);
}
export default Photos;

Now we need a Hook! Create a file in the same directory called hooks.js and fill it with this:

// hooks.js
import { useState, useEffect } from "react";
function useFetch(url) {
const [data, setData] = useState([]);
const [loading, setLoading] = useState(true);
async function fetchUrl() {
const response = await fetch(url);
const json = await response.json();
setData(json);
setLoading(false);
}
useEffect(() => {
fetchUrl();
}, []);
return [data, loading];
}
export { useFetch };

Import the Photos component into App.js and yarn start. Done!

Keep in mind the code here is meant to be small and doesn’t handle anything besides getting an ideal response. You should do something better in real apps. Enjoy!

--

--

Connor Wilson

Engineering Manager @coursera, former Director of Frontend Education at @itsbridgeschool. Building things and teaching folks in Toronto.