Custom Hooks

Building your own Hooks lets you extract component logic into reusable functions. This is useful when you want two JavaScript functions to share some logic.

What is a Custom Hook?

A custom Hook is a JavaScript function whose name starts with ”use” and that may call other Hooks. It's just a convention, but it's essential for React to know that it contains Hooks.

Example: useFetch

Let's say we have logic to fetch data that we want to use in multiple components.

JavaScript

import { useState, useEffect } from "react";

const useFetch = (url) => {
  const [data, setData] = useState(null);

  useEffect(() => {
    fetch(url)
      .then((res) => res.json())
      .then((data) => setData(data));
  }, [url]);

  return [data];
};

export default useFetch;

Using Custom Hooks

Now we can use this `useFetch` hook in any component.

JavaScript

import useFetch from "./useFetch";

const Home = () => {
  const [data] = useFetch("https://api.example.com/todos");

  return (
    <div>
      {data && data.map((item) => <p key={item.id}>{item.title}</p>)}
    </div>
  );
};

Note: Custom Hooks are a mechanism to reuse stateful logic (like setting up a subscription and remembering the current value), but every time you use a custom Hook, all state and effects inside of it are fully isolated.