Refactor a Higher-Order Component to a Render Prop Component

Share this video with your friends

Send Tweet

In this lesson we look at two React components that render a Chuck Norris joke and share common functionality via a Higher-Order Component. We'll refactor this Higher-Order Component to be a Render Prop component to help make it easier to reason about.

Andrew Del Preteinstructor
~ 6 years ago

It's also possible to utilize the Render Prop pattern by passing your component a regular property such as render.

Example: <MyComponent render={(...) => <div>Hello World</div>} />

I use the Function as Children (FAC) approach in this video because it's easier for me to visually understand and prettier does a great job cleaning it up. FAC's are still considered the "Render Prop" pattern because a Component's children are properties.

See: Render Props for more info!

Platon
~ 6 years ago

Are there cases where you'd prefer "traditional" HoCs over FAC?

Andrew Del Preteinstructor
~ 6 years ago

Hey Platon, so far, not in my experience. I've been able to replace HoCs to FAC / Render Props and had good results. HoCs are a little easier to test because the rendered component is separate and you can just import and pass it fake props. With Render Props you have to mount and dig in a bit or make your render prop a component itself that you pass in and test.

See: Testing Component Using Render Props

Platon
~ 6 years ago

Thank you, Andrew!

With some practice I am beginning to see the ease-of-use utility of FAC / Render Props compared to HoCs, especially when the meta-component has to take different dynamic props every time it's reused.

I am looking forward to your future videos! Please make one on your approach to testing FAC / Render Props too, if that's OK : )

Thilo Maier
~ 6 years ago

The codesandbox has the code at the end of the video. If I want to follow along in the video I have to swap index.js for index.hoc.js. And then the index.hoc.js is not what you start with in the video... Ideally there should be one codesanbox that reflects the code at beginning of video and one at end.

Andrew Del Preteinstructor
~ 6 years ago

The codesandbox has the code at the end of the video. If I want to follow along in the video I have to swap index.js for index.hoc.js. And then the index.hoc.js is not what you start with in the video... Ideally there should be one codesanbox that reflects the code at beginning of video and one at end.

Hey Thilo, a cool feature in codesandbox is the Current Module View toggle (top right corner). Open index.hoc.js in the sandbox and toggle to "Current Module View" and it will use index.hoc.js instead of index.js.

I also fixed the HoC example to be closer to that which is in the video. Thanks for the feedback and watching!

Andrew Del Preteinstructor
~ 6 years ago

Hey Platon! That's a great idea. I'll see what I can do!

Thilo Maier
~ 6 years ago

Perfect!