The HOC Drill Pattern
With the rise of Higher Order Component composition in the React community, there are a plethora of libraries, such as my own redux-form, that will add functionality to your application by decorating your component and wrapping it in a HOC.
What you end up with is a component structure like this, where you control the yellow components, MyContainer and MyWrappedComponent, but you have no control over the red code, LibraryHOC.
Most such libraries are polite enough to pass through any props that they do not use as parameters down to your wrapped component, but sometimes they will not provide a way, e.g. getWrappedInstance, to access instance methods on your wrapped component.
What can you do? How can you get through this barrier?
Let’s lay out a concrete example. Your MyWrappedComponent has instance methods of load(), save(), and clear(), and you need buttons in your MyContainer to be able to call these.
How can MyContainer drill through the HOC to call methods on MyWrappedComponent?
Because our HOC allows us to pass props down through it, we can pass a callback that will give our container component references to the wrapped component’s instance methods.
Let’s see that in action. When the inner MyWrappedComponent is going to be mounted, it sends up the API that it wants to expose to MyContainer.
It is a little messy, but breaking through barriers often is. I have used this pattern on several occasions, and it works well.
One important side note: If your wrapped component might be unmounted while your container remains, to prevent a memory leak, you should “unregister” the instance methods via another callback in componentWillUnmount().