ReactJS: custom hooks
ReactJS hooks
reactjs
hooks
custom
description
📘 Custom Hooks
Hooks are reusable functions. When you have component logic that needs to be used by multiple components, we can extract that logic to a custom Hook.
Custom Hooks start with use
.
Example: useFetch
1 Example 1
We are fetching
data, We will use the JSONPlaceholder service to fetch fake data. This service is great for testing applications when there is no existing data.
App.js
import { useState, useEffect } from "react";
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>;
})}
</>
);
};
The fetch
logic may be needed in other components as well, so we will extract that into a custom Hook.
Move the fetch logic to a new file to be used as a custom Hook:
useFetch.js
index.js
We have created a new file called useFetch.js
containing a function called useFetch
which contains all of the logic needed to fetch our data.