This content originally appeared on DEV Community and was authored by Andrew Lee
It's possible to go far without writing our own hooks and instead lean on hooks made by third party libraries. However, we shouldn't shy away from it, at worst it will help us understand how other hooks work.
Let's write our own useFetch
hook to clean up this component.
const SomeComponent = () => {
const [data, setData] = useState(undefined);
useEffect(() => {
const fetchData = async () => {
const res = await fetch("https://someurl.com");
const data = await res.json();
setData(data);
};
fetchData();
}, []);
return <pre>{data}</pre>;
}
The first step to writing our hook is to pretend like it already works. How do we want the API to look like?
const { data } = useFetch("https://someurl.com");
Now that we know how we want the end result to be, we can start filling in the details. One trick is to look for hooks (i.e. useState
, useEffect
) that can be grouped together, and put it inside a new hook.
In this case the useEffect
is used with useState
to set the data. This means we can group them together.
const useFetch = (url) => {
const [data, setData] = useState(undefined);
useEffect(() => {
const fetchData = async () => {
const res = await fetch(url);
const json = await res.json();
setData(json);
};
fetchData();
}, []);
return { data };
}
Now we can use our new hook like this:
const SomeComponent = () => {
const { data } = useFetch("https://someurl.com");
return <pre>{data}</pre>;
}
Writing our hooks is a great way to clean up our components and create bits of code that can easily be used in other components.
This content originally appeared on DEV Community and was authored by Andrew Lee
Andrew Lee | Sciencx (2021-11-28T01:07:45+00:00) Write your first React hook. Retrieved from https://www.scien.cx/2021/11/28/write-your-first-react-hook/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.