3

Write your first React hook

 2 years ago
source link: https://dev.to/andyrewlee/write-your-first-react-hook-553e
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
Andrew Lee

Posted on Nov 28

Write your first React hook

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>;
}
Enter fullscreen modeExit fullscreen mode

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");
Enter fullscreen modeExit fullscreen mode

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 };
}
Enter fullscreen modeExit fullscreen mode

Now we can use our new hook like this:

const SomeComponent = () => {
  const { data } = useFetch("https://someurl.com");

  return <pre>{data}</pre>;
}
Enter fullscreen modeExit fullscreen mode

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.


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK