Driver FixRecommendedSound, Wi-Fi or graphics acting up? Check drivers firstFind missing or outdated drivers fast.Check DriversOctober DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsPC HealthRecommendedCrashes, freezes, slowdowns? Check your PC nowSpot repairable issues before they interrupt work.Check PC×
Skip to content
World desk5 min

Build Safer React Higher-Order Components: A Practical Guide

A practical guide to React HOCs: wrap instead of mutate, pass props deliberately, create stable enhanced components, and choose the right reuse pattern.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

A React higher-order component (HOC) is a function that takes a component and returns a new component with added behavior. Implement it by wrapping—not modifying—the input component, passing through its ordinary props, and creating the enhanced component outside render. HOCs remain useful for component-level reuse and APIs that expect a wrapper; custom Hooks, context, and composition may be clearer for other jobs.

What is a higher-order component in React?

A higher-order component is a component-level composition pattern: a function receives a component and returns another component that renders it with extra behavior or data. The returned component can use Hooks, add or transform props, and decide how the original component is rendered. HOCs are a pattern, not a built-in React API; React’s current reference organizes reusable component features around Hooks and identifies some APIs as legacy. The familiar HOC guide is on React’s legacy documentation site, so use it for the composition pattern and check version-sensitive details against current references.

As an Amazon Associate I earn from qualifying purchases.

Wrapping preserves the original component as a component in its own right. Mutating it instead can make it unusable without the enhancement, make multiple HOCs overwrite each other’s changes, and fail for function components. Composition lets each wrapper add behavior without changing the wrapped component’s implementation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

How do I write a React HOC?

A typical HOC returns a function component that calls a custom Hook, then renders the wrapped component. Define the HOC at module scope and apply it to the component there, not inside another component’s render function.

function withFeature(WrappedComponent) {
  function EnhancedComponent(props) {
    const featureValue = useFeatureValue();
    return <WrappedComponent {...props} featureValue={featureValue} />;
  }

  EnhancedComponent.displayName =
    `withFeature(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;
  return EnhancedComponent;
}

const ProfileWithFeature = withFeature(Profile);

The Hook runs at the top level of the wrapper component, following the Rules of Hooks. The HOC factory returns a component type; calling it during render creates a different type on each render, which can reset the wrapped component’s state and create performance problems. Keep the enhanced component stable by creating it outside render. React’s guidance on component identity is in its Higher-Order Components guide; Hook usage rules are covered in React calls Components and Hooks.

How do I pass props through an HOC?

Pass through the wrapped component’s existing props, and add only the props needed for the enhancement. If the HOC accepts configuration props that should not reach the wrapped component, remove those before spreading the remaining props.

function withFeature(WrappedComponent) {
  function EnhancedComponent({ featureMode, ...wrappedProps }) {
    const featureValue = useFeatureValue(featureMode);
    return <WrappedComponent {...wrappedProps} featureValue={featureValue} />;
  }
  return EnhancedComponent;
}

Here, featureMode configures the wrapper, while wrappedProps preserves the wrapped component’s other inputs. Decide deliberately whether an HOC-provided prop should override a caller’s prop; in the example, the HOC supplies featureValue. Filtering HOC-specific props avoids leaking implementation details into the wrapped component or its DOM output. Keeping the rest of the contract intact makes the enhanced component more reusable. HOCs can also be composed, and some accept configuration in addition to a component.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

What else should a wrapper preserve?

Static properties

A wrapper is a new component, so static methods or properties on the wrapped component do not automatically become statics on the wrapper. If consumers rely on a static member, decide whether and how to expose it on the enhanced component; the React legacy guide discusses this concern. Do not assume that rendering the wrapped component forwards its statics.

Component identity and display names

A stable component type is important for preserving state across renders, so create the HOC result once rather than repeatedly in render. Setting a descriptive displayName, as in the example, also makes the wrapper easier to recognize in debugging tools. React’s legacy guide describes naming and component identity alongside HOC implementation concerns.

Pure rendering and memoization

An HOC does not automatically make a component faster. React’s memo reference describes memoization as an optimization, not a guarantee: a memoized component may still render when its own state or consumed context changes. Independently, components should render purely: for the same props, state, and context, their output should be consistent, and side effects should not run during render. See Components and Hooks must be pure.

How do I forward refs through an HOC?

Ref behavior depends on both the React version and the wrapped component’s kind. In React 19, a function component can receive ref as a prop; new function components no longer need forwardRef. React’s announcement says it plans to deprecate and remove forwardRef in a future version—it has not already been removed. A ref to a class component still refers to the class instance; it is not passed through as an ordinary prop. See the React 19 announcement.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When building a wrapper, decide explicitly what the ref should target: the enhanced function component, a particular element or child, or a wrapped class instance. Do not assume that spreading ordinary props solves ref forwarding, especially across React versions. Check the current ref behavior for the React version and component type your code supports before choosing an implementation.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Should I use a custom Hook or an HOC?

Choose based on where the shared behavior belongs and how you want consumers to see it. A custom Hook shares logic while leaving the consuming component in control of its own returned values and rendering. An HOC shares behavior by returning an enhanced component, which suits component-level APIs or libraries that expect a wrapper. Context makes a value available deep in a tree without threading it through every intermediate component. Composition is useful when callers should control component structure or children.

Pattern Best fit Trade-off to consider
Custom Hook Reusable logic in function components The component calls the Hook and decides how to use its result; shared behavior is visible in the component’s code.
HOC Component-level enhancement or an API that requires a wrapped component Adds a wrapper to the component tree; props, refs, statics, and debugging should be considered.
Context Making information available to descendants without passing it through each intermediate component Use it when tree-wide availability suits the data; it is not simply a component wrapper or a substitute for every form of logic reuse.
Composition Letting a caller control component structure or children Works when the desired reuse is in the assembled structure rather than hidden enhancement.

For function components, React recommends defining a static custom Hook with the desired behavior rather than passing Hooks around as regular values or dynamically transforming them into higher-order Hooks. See React calls Components and Hooks and the built-in React Hooks reference. The practical choice depends on interface visibility, reuse scope, tree shape, local debugging, ref needs, and supported React versions—not on a universal ranking of patterns.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
Windows Errors? Fix Them Before They SpreadFree repair scan

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.