Frontend School
DashboardProblemsLearnPracticeMock InterviewReportsStatsBuy Credits
DashboardProblemsLearnPracticeMock Interview
Machine Coding Patterns
  1. 1.Setting Up for Machine Coding
  2. 2.Interactive UI Basics: Counter & Toggle
  3. 3.Building a Static Component: Star Rating
  4. 4.Handling User Input: Form Elements
  5. 5.Displaying Dynamic Data: Todo List
  6. 6.Filtering & Searching Data
  7. 7.Pagination & Infinite Scroll
  8. 8.Advanced UI Components: Modals & Tooltips
  9. 9.Drag & Drop Functionality (Basic)
  10. 10.Reusability Patterns: Hooks & HOCs
  11. 11.Performance Optimization Techniques
  12. 12.Complex State Management & Architecture
Machine Coding Patterns
10

Machine Coding · Lesson 10 of 12 · 4 min

Reusability Patterns: Hooks & HOCs

This isn't just a React question. It's a design pattern question that tests how you think about abstraction, coupling, and composition.

Start with Custom Hooks for Stateful Logic

For sharing stateful logic between components, custom hooks are the modern default. They let you extract logic, not UI, into a reusable function. A component uses a hook; it doesn't get wrapped or changed by it.

This keeps your component hierarchy flat and makes the data flow explicit. You can see exactly where state and effects come from by reading the first few lines of a component.

A common interview task is to persist some state. A useLocalStorage hook is the canonical example. It combines useState and useEffect to create a powerful, self-contained, and reusable piece of logic.

import { useState, useEffect } from 'react';

function useLocalStorage(key, initialValue) {
  const [storedValue, setStoredValue] = useState(() => {
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch (error) {
      console.error(error);
      return initialValue;
    }
  });

  useEffect(() => {
    try {
      window.localStorage.setItem(key, JSON.stringify(storedValue));
    } catch (error) {
      console.error(error);
    }
  }, [key, storedValue]);

  return [storedValue, setStoredValue];
}

The trap: Candidates often forget the dependency array in useEffect or fail to handle the initial state retrieval from localStorage safely. Another common mistake is violating the Rules of Hooks. The rules exist because React relies on a consistent call order on every render to associate state with the correct hook call.

When to Use a Higher-Order Component

HOCs are for a different job. They are functions that take a component and return a new component, usually wrapping the original. Use an HOC when you need to change the component itself or its environment, not just provide it with state.

This pattern is fundamentally about wrapping and interception.

Good use cases for HOCs include:

  • Conditional Rendering: Rendering a completely different UI based on some condition, like showing a loading spinner or a login prompt instead of the component.
  • Legacy Code: Interfacing with class components that can't use hooks.
  • Context Providers: Wrapping a component in a specific context provider.

In an interview, if you choose an HOC, you must justify why a hook is insufficient. A good answer involves modifying the render output around the component. For example: "I'd use an HOC here because I need to wrap the component in a layout <div> with specific styles and event handlers, which a hook can't do."

The Core Trade-off: Composition vs. Wrapping

The choice between hooks and HOCs boils down to a fundamental design decision.

Custom hooks enable composition. Your component remains in control, pulling in logic as needed. You can use multiple hooks, and their logic is composed together within your component's scope. The flow is "inside-out."

HOCs are about wrapping. They create a parent component that controls its child. This introduces a layer of indirection and can lead to "wrapper hell"—a deeply nested component tree that's hard to debug. The data flow is "top-down."

The trap: A common HOC implementation forgets to forward props or refs. You must pass through all props using {...props}. To forward refs, you need to use React.forwardRef. Forgetting this shows a lack of production experience.

How to Frame Your Answer in an Interview

Your choice signals your design priorities. Frame your answer around these concepts.

| Concern | Custom Hook (useData) | HOC (withData) | | :--- | :--- | :--- | | Coupling | Low. The component calls the hook. | High. The HOC wraps the component. | | Data Flow | Explicit. const { data } = useData() | Implicit. data appears as a prop. | | Debugging | Easy. Flat component tree. | Hard. "Wrapper hell" in DevTools. | | Flexibility | High. Easy to compose multiple hooks. | Low. Composition is verbose and nested. |

When asked to "design an authentication system," don't just pick one pattern. Explain the trade-offs.

A useAuth hook is great for components that need to read user data or access a logout function. An withAuth HOC is better for protecting entire pages by rendering a <Redirect> if the user is not authenticated. They solve different problems. One provides data to a component that will render anyway; the other decides if the component should render at all.

Try it

Implement a useDebounce custom hook that takes a value and a delay. Apply it to a search input. Then, write down the function signature for a withDebounce HOC that would try to achieve the same thing. List two specific reasons why the hook is a cleaner, more effective pattern for this use case.

Next: We'll apply these abstraction patterns to solve rendering bottlenecks in Performance Optimization Techniques.

Lock it in — apply this lesson under interview conditions.

Try a free mock interviewPractice machine coding problems
Previous

Drag & Drop Functionality (Basic)

Next

Performance Optimization Techniques