Lesson 13. From render-props and high-order components to hooks 2. High-order components to hooks
A high-order component (HOC) can be defined as a function that takes a component as parameter, and returns a decorated version of this component. In most cases, the decoration consists in adding some props specific to the HOC.
To use a HOC, you need to first create the decorated component (by calling the HOC function), then use this component:
const MyComponent = () => { return <div>...</div> }const DecoratedComponent = hoc(MyComponent)// ...<div><DecoratedComponent/></div>
In this case the HOC doesn’t take other parameters than the component, but some HOC can take specific parameters; depending on the preference of the HOC’s developer, it can be called as a single function call, or two:
hoc(MyComponent, param1, param2)// orhoc(param1, param2)(MyComponent)
Let’s take the same example as with render-props components, and consider this example of HOC fetching a Reddit story from its URL:
Result
In this example, the RedditStory component takes as parameter a story and
displays its values. To use this component without having to fetch the info by
ourselves, we use the HOC withRedditStory. We create a decorated version of
it, which won’t require any parameter.
Note that another variant of the components using the HOC can make it possible to use the component by passing it the story URL:
const RedditStoryFromUrl = ({ storyUrl }) => {const FetchedRedditStory = withRedditStory(storyUrl)(RedditStory)return <FetchedRedditStory />}const Comp = () => {const url = 'https://www.reddit.com/r/reactjs/comments/gi1rsc'return <RedditStoryFromUrl storyUrl={url} />}
If you observe the withRedditStory function, you’ll notice again that it is
very similar to a custom hook, accepting a parameter storyUrl, and returning a
result, as a prop passed to a component.
Once again, converting this HOC to a hook won’t be any problem. The hook with take as only parameter the story URL, and return —instead of a new component— the resulting story.
Result
Same as render-props components, the HOC you’ll encounter will likely be written as class components. In that case, start by converting them to function-HOC components, then to custom hooks.