Extract React Query useQuery into custom hooks

Tomasz Ducin
InstructorTomasz Ducin
Share this video with your friends

Social Share Links

Send Tweet
Published 7 months ago
Updated 2 months 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.