javascript / intermediate
Snippet
Reusing Logic with Higher-Order Components
A Higher-Order Component (HOC) is a pattern where a function takes a component and returns a new, enhanced component. It is useful for cross-cutting concerns like logging, authentication, or fetching data.
snippet.js
1
2
3
4
5
6
7
8
9
10
11
const withLogger = (WrappedComponent) => {return (props) => {useEffect(() => {console.log(`Component ${WrappedComponent.name} mounted`);}, []);return <WrappedComponent {...props} />;};};const EnhancedButton = withLogger(Button);
react
Breakdown
1
const withLogger = (WrappedComponent) => {
A function that accepts a component as its argument.
2
return (props) => { ... }
Returns a new functional component that wraps the original one.
3
<WrappedComponent {...props} />
Renders the original component with all passed-down props.