Section 0: Full HOC Example
This is an HOC example for you to copy and paste. If you certain pieces don't make sense for you, head to Section 1 to get a detailed walkthrough via a complete translation of the React docs in TypeScript.
Sometimes you want a simple way to inject props from somewhere else (either a global store or a provider) and don't want to continually pass down the props for it. Context is great for it, but then the values from the context can only be used in your render
function. A HoC will provide these values as props.
The injected props
Usage in the component
The goal is to have the props available on the interface for the component, but subtracted out for the consumers of the component when wrapped in the HoC.
Consuming the Component
Now when consuming the component you can omit the primaryColor
prop or override the one provided through context.
Declaring the HoC
The actual HoC.
Note that the {...(props as T)}
assertion is needed because of a current bug in TS 3.2 https://github.com/Microsoft/TypeScript/issues/28938#issuecomment-450636046
Here is a more advanced example of a dynamic higher order component that bases some of its parameters on the props of the component being passed in:
forwardRef
Using For "true" reusability you should also consider exposing a ref for your HOC. You can use React.forwardRef<Ref, Props>
as documented in the basic cheatsheet, but we are interested in more real world examples. Here is a nice example in practice from @OliverJAsh (note - it still has some rough edges, we need help to test this out/document this).