How To Fetch Data From An API With React Hooks

React Hooks is an exciting new feature that allows you to do anything in components of function rather than using classes such as fetch data. A lot of discussions are going on around them, but you’re here to get information!

In this tutorial, I want to show you how to fetch data in React with Hooks by using the state and effect hooks.

Refactoring from a class to functional component

Our first step to using hooks would be to refactor it to a functional component. Remember, you use hooks only with functional components. Fetching data with the fetch API and React class component

In the above code, The component has a hasError and a planets state. If the component mounts, we call the Starwars API and fetch the information.

Here’s how would transform the Class component to a functional component.

UseEffect is a React hook that accepts a callback as the first argument. Inside the first argument, we do all the tasks related to the effect. So, Import the useEffect from the React package, and replace the componentWillMount with the fresh hook.

What does useEffect do?

By using this Hook, you tell React that after rendering, your component needs to do something. React will remember the function you passed (we’ll refer to it as our “effect”), and call it later after DOM updates have been made.

In the above code, Hooks don’t have lifecycle effects such ascomponentDidMount or componentWillMount

Note:- If you want the useEffect to behave like the componentDidMount lifecycle event, pass an array as the second argument, like so;

Consider the second argument as the dependencies for that effect. The impact will run again if one of the dependencies has changed since the last time.

Hooks in ReactJS

Effect Hooks in ReactJS

Custom Hook in React JS

Related posts