Refactor a render Prop Component to a Custom React Hook

Share this video with your friends

Send Tweet

Our <Query /> component is a render prop based component that the <User /> component uses. But because it doesn't render anything, we can actually just change it to a custom hook. Let's create a useQuery hook that returns the state from the hooks the Query component uses and use that instead. But we'll preserve the component so we don't have to refactor everywhere that uses the Query render prop based component as well and we can keep our tests passing as they are.

Platon
Platon
~ 6 years ago

Great course as always, two points I would like to ask you expand on if you ever had time:

  1. getFooProps pattern (from your previous course) with hooks
  2. examples of useMemo to optimize components

Again, thank you and looking forward to your next videos!

Platon
Platon
~ 6 years ago

Another thing - how would you handle defaultProps, propTypes etc for React functions that return state (these don't seem to work)?

Kent C. Dodds
Kent C. Dodds(instructor)
~ 6 years ago

Hi Platon! You mean how do you use propTypes and defaultProps for custom hooks?

For propTypes I recommend using TypeScript or Flow instead.

For defaultProps, use default values, just like we do with the normalize function here:

function useQuery({query, variables, normalize = data => data}) {
  // ...
}

I hope that helps.

Platon
Platon
~ 6 years ago

Thanks, that helped.

Have you thought of making some educational material on implementing the getProps pattern from your previous course with hooks, or the useMemo for optimizing components with the return state (along with component as default export) pattern from this course?

Cheers!