javascript / expert
Snippet
Ref Forwarding in Higher-Order Components
When wrapping a component in an HOC, the 'ref' property is not passed down automatically because it is a reserved prop like 'key'. By using 'forwardRef', you ensure that the parent can still access the underlying DOM node or component instance of the wrapped element, maintaining the expected API of the component.
snippet.js
1
2
3
4
5
6
7
8
9
function withLogger(WrappedComponent) {const LoggedComponent = forwardRef((props, ref) => {useEffect(() => console.log('Component rendered with:', props), [props]);return <WrappedComponent {...props} ref={ref} />;});LoggedComponent.displayName = `withLogger(${WrappedComponent.displayName || WrappedComponent.name || 'Component'})`;return LoggedComponent;}
react
Breakdown
1
forwardRef((props, ref) => { ... })
Special React utility that explicitly captures the ref passed to the component.
2
return <WrappedComponent {...props} ref={ref} />;
Passing the captured ref down to the actual component being enhanced.
3
LoggedComponent.displayName = ...
Essential for debugging: sets a readable name in React DevTools.