How to Load Data Easily With React Hooks
Building React components is an art. There are many different ways to achieve similar results. You can use purely functional components or classes. You can build complex HOCs or keep everything flat. There are a lot of options when it comes to composition. With all these different choices, even implementing a simple data loading method might seem like a daunting task.
With a recent iteration of the prescribed ways to construct React components, the React team suggests creating functional components. Rather than rely on extending the React.Component
class to create a component, you simply define a function. With this way of building components comes the ability to use Hooks. A React Hook is essentially a function that allows you to perform some actions at specific parts of the component lifecycle.
The most commonly used Hook, aside from useState
, is useEffect
. In this article we’ll explore how to implement useEffect
to load some data into your functional component. We’ll also leverage useState
to setup some persistent values inside our component as well. The final product will be a simple, effective component that fetches data in a concise manner and can be easily extended.
We’ll also assume that you already have a basic React app setup and working. Setting up a new app and explaining how components interact is beyond the…