Loading...
Loading...
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.
const withExtraLogic = (WrappedComponent) => {
return function EnhancedComponent(props) {
// Additional logic
return <WrappedComponent {...props} />;
};
};
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.
Often used for:
connect)...props to pass them furtherfunction 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.