I am learning about custom Hooks in React. I have taken the following typical example (useFetch
) as you can see in https://www.w3schools.com/react/react_customhooks.asp.
import { useState, useEffect } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null); /* <--- Why use this? */
useEffect(() => {
fetch(url).then((res) => res.json()).then((data) => setData(data));
}, [url]);
return [data];
};
export default useFetch;
I'm confused why state should be used inside that Hook, or in general in custom Hooks. I always relate state management to components, not to a hook. Hence perhaps my confusion.
Couldn't it have been done simply by returning a data variable?