Home > Blockchain >  Why or when should I use state within a custom Hook in React?
Why or when should I use state within a custom Hook in React?

Time:05-17

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?

CodePudding user response:

Unlike normal functions, custom hooks encapsulates React state. This means that the hook can utilize react's own hooks and perform custom logic. It's quite abstract in that sense.

For your case, you want to return the state of the data, not just the data by itself because the state is tied to a useEffect. That means that fetch will only run and by extension only update data when its dependencies ([url]) are changed.

If it was a normal function just returning the data from the fetch, you would send a request every time the component using the hook re-renders. That's why you use useState coupled with useEffect to make sure it only updates when it should.

  • Related