Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
React Interview Essentials
  1. 1.Introduction to React & Basic Setup
  2. 2.JSX, Functional Components & Props
  3. 3.State Management with useState & useEffect
  4. 4.Conditional Rendering & List Management
  5. 5.Event Handling & Form Management
  6. 6.React Router for SPA Navigation
  7. 7.Context API for Global State
  8. 8.Working with Refs & the DOM
  9. 9.Advanced Component Patterns: HOCs & Render Props
  10. 10.Building Reusable Logic with Custom Hooks
  11. 11.Performance Optimization with Memoization
  12. 12.Error Boundaries for Robust UIs
  13. 13.Concurrent React & Suspense
  14. 14.Testing React Components with RTL
  15. 15.Advanced State Management (Overview)
React Interview Essentials
09

React · Lesson 9 of 15 · 4 min

Advanced Component Patterns: HOCs & Render Props

These patterns are less common now, but interviewers use them to test your understanding of component composition and the problems that led to Hooks.

After this lesson, you'll be able to explain the trade-offs between HOCs, Render Props, and Custom Hooks. This isn't just about legacy patterns; it's about showing you understand why the ecosystem evolved. The question is rarely "write an HOC." It's "compare these patterns."

Why these patterns still matter

Hooks have replaced HOCs and Render Props for most new development. Let's be clear about that. You will not be writing many of these in a modern codebase.

So why learn them? First, you'll encounter them in older, established codebases. Second, they are the direct predecessors to Hooks. Understanding their limitations—wrapper hell, prop collisions, JSX nesting—is crucial for explaining why Hooks are an improvement. Answering this well shows depth.

The interview question about HOCs is often a setup for the follow-up: "Now, how would you solve this with a custom hook?"

How Higher-Order Components work

A Higher-Order Component (HOC) is a function that takes a component and returns a new, enhanced component. It's a pattern borrowed from functional programming that uses composition to share logic.

Use HOCs for applying static, cross-cutting concerns. Think logging, injecting a theme from context, or checking authentication status. The logic is applied once, outside the component's render lifecycle.

// A simple HOC that provides a 'styles' prop.
function withStyles(WrappedComponent, styles) {
  // It returns a new component...
  return function(props) {
    // ...that renders the original component with extra props.
    return <WrappedComponent {...props} styles={styles} />;
  };
}

// Usage
const Button = ({ styles, ...props }) => (
  <button style={styles.button} {...props} />
);

const primaryButtonStyles = { button: { background: 'blue', color: 'white' } };
const PrimaryButton = withStyles(Button, primaryButtonStyles);

// In your app: <PrimaryButton>Click Me</PrimaryButton>

The trap: HOCs introduce several problems that you must be able to articulate.

  1. Wrapper Hell: Applying multiple HOCs results in a deeply nested component tree in React DevTools, which is difficult to debug. withAuth(withTheme(withRouter(MyComponent))) is a classic example.
  2. Prop Collisions: If an HOC injects a prop named user and your component already receives a user prop, the HOC's prop will overwrite it silently. This can lead to subtle bugs.
  3. Opaque Logic: It's not immediately clear from the JSX where the props are coming from. You have to find the component's definition to see which HOCs are wrapping it.
  4. Ref Forwarding: Refs are not passed through by default. A ref on an HOC-wrapped component will point to the wrapper, not your inner component. You have to explicitly use React.forwardRef to fix this, adding boilerplate.

How Render Props work

The Render Prop pattern uses a prop (usually render or children) whose value is a function. The component calls this function with its internal state, giving the parent component full control over the rendering logic.

This pattern makes the data flow explicit. You can see exactly what state is being shared right in the JSX. It's better for sharing dynamic state that changes over time, like mouse coordinates or toggle state.

Here is the classic MouseTracker example. The component itself has no visual output; it just manages state and calls the function you provide.

import React, { useState } from 'react';

function MouseTracker({ children }) {
  const [position, setPosition] = useState({ x: 0, y: 0 });

  const handleMouseMove = (event) => {
    setPosition({
      x: event.clientX,
      y: event.clientY,
    });
  };

  return (
    <div style={{ height: '100vh' }} onMouseMove={handleMouseMove}>
      {children(position)}
    </div>
  );
}

// Usage in another component
function App() {
  return (
    <div>
      <h1>Move the mouse around!</h1>
      <MouseTracker>
        {({ x, y }) => (
          <p>The current mouse position is ({x}, {y})</p>
        )}
      </MouseTracker>
    </div>
  );
}

The relationship is clear: MouseTracker provides data to a function that the parent defines.

The trade-off: Render props solve the prop collision and opaque logic problems of HOCs. However, they can introduce their own form of nesting inside the JSX, sometimes called "callback hell," which can be hard to read if multiple render props are used together.

The interview answer: HOCs vs. Render Props vs. Hooks

This is the real question. Your answer should show you understand the evolution of these patterns.

In an interview, frame your answer like this:

"All three patterns solve the same core problem: reusing stateful logic across components.

HOCs are functions that wrap a component, injecting props. They're good for static, cross-cutting concerns but suffer from issues like prop collisions and 'wrapper hell' in the component tree. The logic source is also implicit.

Render Props invert the control. A component takes a function prop and calls it with its state, making the data flow very explicit in your JSX. This avoids prop collisions but can lead to deeply nested JSX.

Custom Hooks are the modern solution. They let you extract and reuse stateful logic without adding components to the tree. They solve the problems of both HOCs and Render Props: there's no wrapper hell, no prop collisions, and the data flow is as explicit as a function call. For almost any new logic-sharing need, a custom hook is the correct choice today."

This answer is balanced, shows historical context, and demonstrates a clear preference for modern best practices. It proves you're not just reciting definitions.

Try it

Implement a Toggle component. It should manage a boolean isOn state and a toggle function. First, build it using the render prop pattern where children is a function. Then, refactor that logic into a useToggle custom hook to see how much cleaner it becomes. This exercise directly bridges this lesson with the next.

Next: Building Reusable Logic with Custom Hooks, where we'll explore the modern solution to these problems in depth.

Lock it in — apply this lesson under interview conditions.

Try an AI mock interview
Previous

Working with Refs & the DOM

Next

Building Reusable Logic with Custom Hooks