Photo by Kasia Derenda on Unsplash
Day 45- Custom Hooks Cont'd
Hi and welcome to day 45 of my 100 days of code challenge!πͺβ€
Table of contents
Creating a Custom Hook
We typically consider two main reasons to create a custom hook:
If you have a section of code that doesn't directly deal with how things appear on screen (the non-visual part), and you find yourself using that same code in multiple places, you might want to turn it into a custom hook.
If you have a component that's getting really long and complex, you can break it down into smaller pieces by creating custom hooks for specific parts of its functionality. This will make your code easier to read and maintain.
Building on the tipsπ from yesterday, let's dive into creating our own custom hook.ππͺ
As a first step, let's extract the useEffect
responsible for data fetching from our App
component and create a custom hook for it. This involves extracting a significant portion of the App
component's functionality.ππ
As a second step, I'm creating a new function called useMovies
. I created a file named useMovies.jsx
in our source directory. Inside this file, I'll define a function named useMovies
and export it using a named export statement, adhering to the convention of named exports for custom hooks. While not mandatory, this approach helps keep the code organized, with default exports typically used for components.
For the third tip, we use the useEffect
hook which encompasses core logic inside the useMovies
function. However, after saving, we realize that additional elements are needed beyond this. To make the useMovies
function fully functional, it also require additional state variables like movies, isLoading, and error, as fetching movies typically involves managing these states.ππ
Adding necessary state variables: Now within useMovies
, we'll leverage React's useState
and useEffect
hooks to manage state and perform side effects. To achieve this functionality, we need to include the necessary state variables, movies
, isLoading
, and error
and note this was also extracted from the App
componentππ
Handling missing information: Our custom hook also needs to handle situations where the key
or query
are missing. We can achieve this by making the query
a parameter to our function. Remember, this is a function, not a component, so it accepts parameters rather than props.ππ
For the fourth tip π, the useMovies
hook returns an object containing the state variables movies, isLoading,
and error.
ππ
Using the custom hook: We destructure the returned object ({ movies, isLoading, error }
) into individual variables for use within our App
component. These variables will replace the corresponding states that the App
component previously relied upon. Finally, we call our custom hook, passing the necessary query as an argument.
Same resultππ
Thank you for reading.ππ