16Fetching and Caching Data

It's possible to build great user interfaces that are self-contained and don't need to interact with the outside world (such as many games, calculators, and utilities). But, most web apps have a need to receive and store data.

In this chapter, you'll learn:

  • When to fetch and store data in React.
  • How to use window.fetch.
  • What promises are.
  • How async/await works.
  • How to simplify network requests with Axios.
  • How to store data in localStorage.
  • How to read data from localStorage.

ASYNCHRONOUS CODE: IT'S ALL ABOUT TIMING

Whenever you update state, do a side effect, or store data in the user's browser, these tasks take time. One of the trickiest, but also most important, skills that a React developer needs to have is learning how to properly handle asynchronous tasks.

With state updates, ReactDOM handles everything for you. You simply call setState (in a class component) or pass data to a function returned by the useState hook (in a function component). Most of the time, the asynchronous nature of setting React state is seamless and invisible to the developer and the user.

With network and cache requests, on the other hand, every request has the potential to adversely impact the user experience. In the worst case, a remote resource won't be available. More often, the amount of time a request takes will be wildly variable, depending on the user's internet connection, network congestion, and the remote server's current workload.

JavaScript itself is rarely ...

Get Beginning ReactJS Foundations Building User Interfaces with ReactJS now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.