How to fetch data in React

By Tom Hastjarjanto and Editors

Introduction

In this post I will show you how to fetch data in React. I will show you how to fetch data in React using the useEffect hook and I will show you how to fetch data in React using the useReducer hook.

Fetch data in React using useEffect

The useEffect hook is used to perform side effects in React. In this example I will show you how to fetch data in React using the useEffect hook.

import React, { useEffect, useState } from "react";

export default function FetchDataInReact() {
  const [data, setData] = useState([]);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((data) => setData(data));
  }, []);

  return (
    <div className="App">
      <ul>
        {data.map((item) => (
          <li key={item.id}>
            {item.title} {item.completed ? "✅" : "❌"}
          </li>
        ))}
      </ul>
    </div>
  );
}

Fetch data in React using useReducer

The useReducer hook is used to store state in React. In this example I will show you how to fetch data in React using the useReducer hook.

import React, { useReducer, useEffect } from "react";

const initialState = {
  loading: true,
  error: "",
  data: [],
};

const reducer = (state, action) => {
  switch (action.type) {
    case "FETCH_SUCCESS":
      return {
        loading: false,
        error: "",
        data: action.payload,
      };
    case "FETCH_ERROR":
      return {
        loading: false,
        error: "Something went wrong!",
        data: [],
      };
    default:
      return state;
  }
};

export default function FetchDataInReact() {
  const [state, dispatch] = useReducer(reducer, initialState);

  useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((response) => response.json())
      .then((data) => dispatch({ type: "FETCH_SUCCESS", payload: data }))
      .catch((error) => dispatch({ type: "FETCH_ERROR" }));
  }, []);

  return (
    <div className="App">
      {state.error && <div>{state.error}</div>}
      {state.loading ? (
        <div>Loading...</div>
      ) : (
        <ul>
          {state.data.map((item) => (
            <li key={item.id}>
              {item.title} {item.completed ? "✅" : "❌"}
            </li>
          ))}
        </ul>
      )}

Tom Hastjarjanto has been using React.js since 2015. Connect with him at Twitter or LinkedIn.