Curriculum
Course: React
Login

Curriculum

React

Text lesson

Custom Hooks

Hooks are reusable functions that allow you to extract component logic for use across multiple components. Custom Hooks, which start with “use” (e.g., useFetch), encapsulate and share this logic.

Build a Hook

In the following code, we fetch data in the Home component and display it using the JSONPlaceholder service, which provides fake data for testing.

To learn more, refer to the JavaScript Fetch API section. Fetch “todo” items from JSONPlaceholder and display their titles on the page.

Example:

index.js:

import { useState, useEffect } from "react";
import ReactDOM from "react-dom/client";

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

 useEffect(() => {
    fetch("https://jsonplaceholder.typicode.com/todos")
      .then((res) => res.json())
      .then((data) => setData(data));
}, []);

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

Extract the fetch logic into a custom Hook by moving it to a new file for reuse in other components.

Example:

useFetch.js:

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;

index.js:

import ReactDOM from "react-dom/client";
import useFetch from "./useFetch";

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

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

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<Home />);

Example Explained

We created a useFetch.js file with a useFetch function that encapsulates the data-fetching logic.

The hard-coded URL was replaced with a variable that can be passed to the Hook, and we return the data from the Hook. In index.js, we import and use useFetch like any other Hook, providing the URL to fetch data from, allowing us to reuse this Hook across components.