Day 17 of 50 Days of React: Custom Hooks in React.

Aman Khan
2 min readAug 2, 2022

--

Hi Dev’s👋🏻, Lets see what are Custom Hooks in React?

Hooks are reusable functions.

When you have a 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: useFetchApi

We can use that function that hooks in various API calls also you can give arguments to it.

Example: In useFetchApi.js

import { useState, useEffect } from "react";const useFetchApi = (url) => {
const [data, setData] = useState(null);
useEffect(() => {
fetch(url)
.then((res) => res.json())
.then((data) => setData(data));
}, [url]);
return [data];
};
export default useFetchApi;

Now you can use the above hook in any file.

For example: In index.js

import ReactDOM from "react-dom/client";
import useFetchApi from "./useFetch";
const Home = () => {
const [data] = useFetchApi("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 />);

We have created a new file called useFetchApi.js containing a function called useFetchApi which contains all of the logic needed to fetch our data.

Lastly, we are returning our data from our Hook.

In index.js, we are importing our useFetchApi Hook and utilizing it like any other Hook. This is where we pass in the URL to fetch data from.

Now we can reuse this custom Hook in any component to fetch data from any URL.

In the next article I will be writing about Conditional Rendering🤔 ?

That’s all for Today, Stay Tuned and I will see you in the next one👋🏻.

Link to Day 18

Thanks for Following and Claps😋

--

--

Aman Khan

Blockchain and Web3 Engineer Crafting compelling stories at the intersection of tech, business, and culture.