Mastering Higher-Order Components in React: Simplify State & Lifecycle

This article explains what higher-order components are, how they relate to higher-order functions, and provides a step‑by‑step guide with code examples to extract shared state and lifecycle logic in React components.

Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Tencent IMWeb Frontend Team
Mastering Higher-Order Components in React: Simplify State & Lifecycle

Higher-order components (HOCs) are a powerful technique for refactoring React code, allowing you to extract reusable logic for state and lifecycle methods.

What is a higher-order component? The term comes from higher‑order functions—functions that take another function as an argument and may return a new function. Common examples include Array.forEach, Array.map, and setTimeout.

An HOC receives a component as an argument and returns a new component that wraps the original one, meaning the argument must be a function.

Below is a typical HOC example:

Extract shared state

If two components need to load the same data, they will share the same componentDidMount logic.

1. Find duplicate code

Each component’s constructor and componentDidMount perform the same tasks, and both display the “Loading...” text while fetching data. These duplicated parts are good candidates for extraction into an HOC.

2. Migrate duplicate code to an HOC

In the BookLoader HOC, the book state is managed and passed to the wrapped component as a prop. The same approach handles the Loading state, fetching data and updating the component.

3. Wrap components and replace state with props

Apply the BookLoader HOC to BookDetails and BookSummary components:

4. Simplify further

After migrating to an HOC, you can further simplify the components; in this example the components become plain functional components.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

State ManagementReactHigher-Order Component
Tencent IMWeb Frontend Team
Written by

Tencent IMWeb Frontend Team

IMWeb Frontend Community gathering frontend development enthusiasts. Follow us for refined live courses by top experts, cutting‑edge technical posts, and to sharpen your frontend skills.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.