Higher-Order Component

A function that takes a component and returns a wrapped version with extra behavior or props, such as authentication or store data.

a function that wraps my componentthe withSomething wrapperadd behavior without editing the componentcomponent goes in, upgraded component comes outwrapper that hands extra props to my componentthe connect() thing from old Redux codehigher order componantwhy is my component wrapped in another function call

See it

Live demo coming soon

What it is

A higher-order component, or HOC, is a function that accepts a React component and returns a new component with extra behavior or props. Names usually start with 'with', such as withAuth or withTheme. React Redux's connect is the famous production example: it wraps a component and feeds selected store data into it. React Router's withRouter and React.memo itself are the same shape.

Reach for an HOC when the enhancement belongs at the component boundary and must be applied to many components, especially in an older React codebase already built around wrappers. Hooks are usually clearer for new function components, but they cannot wrap a component from the outside or replace it before rendering.

Gotcha: wrappers can swallow props, refs, static properties, and useful names in React DevTools. Create the enhanced component once at module scope, pass unrelated props through unchanged, set displayName, and document whether refs and non-React statics are preserved.

Ask AI for it

Create a withAuth higher-order component that accepts a React.ComponentType<P> and returns a component with the same public props. Read authentication from the existing AuthContext, render a loading state while it resolves, redirect signed-out users with Next.js useRouter, and otherwise render the wrapped component while passing every original prop through unchanged. Define the wrapper at module scope, set displayName to withAuth(ComponentName), and explain whether ref and static properties are preserved.

You might have meant

component compositioncomponentheadless componentprops vs statecomponent lifecycle

Go deeper