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
const withExtraLogic = (WrappedComponent) => {
return function EnhancedComponent(props) {
// Additional logic
return <WrappedComponent {...props} />;
};
};
HOC Example: props logging
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
...propsto pass them further - HOCs can be combined, but it's important not to overcomplicate the chain
HOC Example with useEffect
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.