Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading