Implementing a Higher Order Component
Explore how to implement higher order components (HOCs) in React to centralize data fetching and pass it to flexible layout components. Understand the benefits of separating container and presentation logic for easier testing and reuse, using examples like cryptocurrency price displays.
Creating a container component
Assume we want to switch between a list and map view in a user interface. A container component will be in charge of gathering the data which is needed for the user and will pass them to the configurable layout component. As long as both components keep to the interface the developer has set up (think PropTypes), both components are easily interchangeable and can be tested and developed independently.
But enough of the theory. Let’s look at an example. We are going to load a list of the 10 biggest cryptocurrencies and their current price. To obtain the data from the Coingecko API, we create a higher order component that loads the data and passes it to the layout component:
Voila! We have written a higher-order component to obtain the data of the crypto prices from CoinGecko. But the higher-order component itself is not enough to make this work. We also need to define a layout component to which we delegate the task of displaying the data.
Creating a layout component
To create a layout component, we define a generic PriceTable component that does not know about
which data exactly it displays. It could be current yogurt prices from the local ...