we are going to talk about making a custom hook!
We are going to make the fetch code a bit reusable. To get things starting, you should have this running:
npx JSON-server — watch data/data.json — port 8000
Then start by creating a file in the src folder call it “useFetch.js.” We need to put the keyword “use” in front of the custom hook, or it won't work.
After you do that, it should look like this:
we are going to want to cut and paste the useEffect (all of it ) into the new useFetch() from Home.js like so:
we copy the whole use effect into the new useFetch.js, and we don't need to change much in this.
But, we do need to change things….
We first need to change line 10 where it says fetch (originally it said localhost:3000…etc.) but, we don't want to hardcode it for reusability!
Now we have just a “URL” property to make it reusable. We will pass in the URL when calling this hook in the future. lastly, we put “URL” as a dependency in the useEffect(line 26), so whenever the URL changes it will rerun that data from the endpoint.
We also need to grab the hooks from Home.js if you haven't already lines5–7. Then instead of blogs on line 5, we change it to “data” since we want it to be reusable; we don't want it to say blogs all the time in later uses. Don't forget to change line 18 as well from setblogs to setData.
next, we have to return some values when using this hook line 28:
you know how we have values in the hooks like this:
line 5–7, the values we are talking about are data, isLoading, error! We need to be able to return something from the useFetch custom hook. we will return an object with three values which once again are on line 28:
we do this, so when we call this function, we can grab those properties or data from the hook!
OK, moving on!
now let's hop over to home.js, and let's destructure the three properties! (we do this just like any other useState hook) like so (line 6):
On line 6, we are destructuring the data with (data, isloading, error), then we set that to useFetch() and pass in a “URL”. This should auto import, but if it doesn't, then don't forget to import all the way on the top.
Finally, to wrap up I change the way the data would read when using it(line 6 data: blogs). I simply said when calling data I'm going to use the word blogs instead, for this component only.
At the end of all that, your two files should look like this:
Well hope that helped, I kept this one short because I had trouble understanding this when I first started. Check out my other work down below. Also, as always I will add the next part of the whole series as the week’s go by.
The Social Media…