mediumFrontend

What are Higher-Order Components (HOCs) in React?

387 views
01

Understand the problem

Define Higher-Order Components, explain their structure, and their use cases.

hocreusabilitycompositiondesign patterns
02

Attempt it yourself

Sketch your approach before reading the solution — that's what interviews test.

Stuck? AI Nudge Available

Get a conceptual hint to guide your logic without spoiling the final implementation.

03

Study the solution

The solution is waiting

Give it an honest attempt first — then compare your thinking with the full walkthrough.

04

Read the code

A withLoading HOC
function withLoading(Component) {
  return function Wrapped({ isLoading, ...props }) {  // forward other props
    if (isLoading) return <p>Loading…</p>;
    return <Component {...props} />;
  };
}

function UserList({ users }) {
  return <ul>{users.map((u) => <li key={u}>{u}</li>)}</ul>;
}

const UserListWithLoading = withLoading(UserList);

export default function App() {
  return (
    <div style={{ padding: 24, fontFamily: "system-ui" }}>
      <UserListWithLoading isLoading={false} users={["Ada", "Grace"]} />
    </div>
  );
}
05

Join the discussion

Discussion (0)

Sign in to join the discussion.

No responses yet. Be the first to share what you think.