Making fetch requests using React.js hooks

Syd Bailey
2 min readJan 11, 2020

--

A picture of a hook — how clever of me.

You’re probably here because you’ve realized the magic of React hooks and are moving some of your class components to functional components to simplify your code/make it cleaner. If not, you’ve probably stumbled across this page and are wondering why it’s even necessary to move from classes to hooks. On a high level, here’s a few solid reasons to use functional components instead of classes, and utilize hooks:

  • less boilerplate code (no need for constructors, state, etc)
  • increased optimization
  • no need to change your functional components to manage state

Here’s a brief explanation of useEffect in React and how we can use this built-in in lieu of componentDidMount, componentWillUpdate and componentDidUnmount with hooks.

You’re familiar with a class component with a fetch request. It looks something like this:

According to React, “by using this hook (useEffect), you tell React that your component needs to do something after render”.

We’ll replace our class entirely with a functional component using arrow notation, erase our constructor and use hooks to set our data in state, and to fetch data from an API.

Let’s walk through what each line means:

In line 5, we are using the useState hook so that we may have access to a state inside of SampleUsingHooks component. I have two variables, data and setData — the equivalent to this.setState({ data: data }) in a class component.

In line 7, we are using the useEffect hook to make our API call, which would replace our componentDidMount and/or componentWillUpdate in a class component. This lets our component know that some rendering will need to occur after we receive a response from our API call.

On line 11, we are using the setData variable created in line 5 to set the state of data in our component. There’s no longer a need for this.setState, making our code a lot more readable.

On line 13, I’ve passed in an empty array as a second argument to my useEffect hook to avoid looping, so that my effect is only called on mount and unmount.

Hope this is helpful — please leave any comments you may have below :) Go forth and code.

— Syd

--

--