Extract React Query useQuery into custom hooks

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet
Published 5 months ago
Updated a week ago

useQuery follows the rules of hooks. You can wrap it in a custom hook for convenience if you want to layer in some additional functionality.

[00:00] Create a new hook. Since we've been loading the employees data using the use query hook, let's call it use employees query. And the whole content for now, initially, of the hook is just going to be the definition and 1st and foremost, the configuration over here for the [00:20] use query. So let's just return it over here and let's make sure that all the imports that we've had are also imported within the file. And right now, we're just going to simply use the hook in this place. So the change that we have made is that from now on, the hook is the same, but the employees [00:40] page component doesn't need to know all the complexity about React Query, all the settings, how it's defined, what is the key. But also if we wanted to use any other custom hooks, like related to different state management solutions or just native hooks, we could just put them and expose them combined just [01:00] as the use employees query. So the component is simpler, but also if there are multiple components which would like to use this hook, there is basically one reusable thing that different components can use without making changes in multiple places.

egghead
egghead
~ 23 minutes ago

Member comments are a way for members to communicate, interact, and ask questions about a lesson.

The instructor or someone from the community might respond to your question Here are a few basic guidelines to commenting on egghead.io

Be on-Topic

Comments are for discussing a lesson. If you're having a general issue with the website functionality, please contact us at support@egghead.io.

Avoid meta-discussion

  • This was great!
  • This was horrible!
  • I didn't like this because it didn't match my skill level.
  • +1 It will likely be deleted as spam.

Code Problems?

Should be accompanied by code! Codesandbox or Stackblitz provide a way to share code and discuss it in context

Details and Context

Vague question? Vague answer. Any details and context you can provide will lure more interesting answers!

Markdown supported.
Become a member to join the discussionEnroll Today