Skip to main content
Practice Problems

What is HOC (higher-order component) in React

HOC (Higher-Order Component) is a function that takes a component and returns a new component with additional logic.

This is a code reuse pattern in React — it allows wrapping base components, extending their functionality without modifying source code.


Syntax

jsx
const withExtraLogic = (WrappedComponent) => { return function EnhancedComponent(props) { // Additional logic return <WrappedComponent {...props} />; }; };

HOC Example: props logging

jsx
function withLogger(WrappedComponent) { return function LoggerComponent(props) { console.log("Props:", props); return <WrappedComponent {...props} />; }; } const Hello = ({ name }) => <h1>Hello, {name}</h1>; const HelloWithLogger = withLogger(Hello); // Usage <HelloWithLogger name="World" />;

At each render you'll see current props passed to component in console.

Where HOCs Are Used

Often used for:

  • Authorization (wrapping components accessible only to authorized users)
  • Redux connection (connect)
  • Layout wrapping (e.g., with themes, languages)
  • Adding common handlers or side-effects

Important to Remember

  • HOC doesn't modify passed component, but creates new one
  • Always copy props using ...props to pass them further
  • HOCs can be combined, but it's important not to overcomplicate the chain

HOC Example with useEffect

jsx
function withFetch(WrappedComponent, url) { return function ComponentWithData(props) { const [data, setData] = useState(null); useEffect(() => { fetch(url) .then((res) => res.json()) .then(setData); }, [url]); return <WrappedComponent {...props} data={data} />; }; }

Now any component can be wrapped in withFetch to get data from API.

Conclusion:

HOC is a powerful way to reuse logic between components without code duplication. It's especially useful when writing cross-component functionality: loggers, route protection, data handling, etc.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.

Finished reading?
Practice Problems