Multiple Higher-Order Components

Learn how to work with multiple higher-order components, timers, and how to test them.

Stacking higher-order components

In React, a set of props can flow from one wrapper component to another, down a practically limitless chain, receiving modifications from each component. This creates infinite possibilities for combining HOCs. Extracting small pieces of functionality into HOCs, instead of allowing components to grow in complexity, is an important skill for keeping a React codebase manageable.

In this section, you’ll add a new feature to Carousel. It’s the ability to auto-advance the slideIndex on Carousel with a timer. All of the timer logic will be encapsulated in a new HOC.

Working with timers

Let’s create a new HOC called AutoAdvances. It’ll be designed to work inside of a HasIndex, calling the increment function it receives after a certain time interval. The interval will be specified by a prop with a default value of 10 seconds. The HOC should take two arguments, specifying which prop it should increment and which it should use to compute the upper bound for the increment function. The internal timer will reset every time the target prop (e.g., slideIndex) changes so that the carousel doesn’t auto-advance immediately after the user switches slides using the “Prev” or “Next” buttons.

  • Start by creating a dummy implementation:
  // src/AutoAdvances.js
  import React from 'react';

  export default (Component, propName, upperBoundPropName) =>
    class ComponentWithAutoAdvance extends React.PureComponent {
      static displayName = `AutoAdvances(${Component.displayName ||
      Component.name})`;

      render() {
        return <Component {...this.props} />;
      }
    };
  • Then formalize the HOC’s requirements as a suite of tests. For the sake of brevity, all of the tests are presented at once below. If you’re trying to practice TDD, you should add one test at a time, then modify the implementation to make that test pass before adding the next one:

Get hands-on with 1400+ tech skills courses.