Objectives
What are React Custom Hooks
Functions of React Custom Hooks
How to Create React Custom Hooks
How to use React Custom Hooks
React Custom Hooks are created to help developers eliminate the need to write repetitive codes. It makes the development process cleaner and faster.
As a React developer, you must have heard of the word hooks, in simple terms, hooks are functions that do something for us. There are varieties of hooks but sometimes we find out that we end up repeating the same codes and this is what hooks solve.
It is also worth knowing that a key feature of React is its re-usability and hooks are no exception.
To create a custom hook, there are some things we need to note.
They follow react hooks rule
They use existing hook
They have the "use" in front of the hook name as a convention to make developers know it is a custom hook
They are like a regular react component
Now, let's dive into the code aspects.
First, we need to create a new React project. So open your terminal and type
yarn create vite
Then select React as your template then follow the prompt. Once the installation is complete, enter the project directory (folder). To do so, type
cd nameOfProject
Then to open the project in a code editor like VSCode, type
code.
Congratulations!!! You have just successfully completed the first round
In your src folder create a folder name hooks and create a file name useFetch.js and paste the following code.
import { useEffect, useState } from "react";
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
if (url) {
setLoading(true);
fetch(url)
.then((response) => response.json())
.then((data) => {
setData(data);
setLoading(false);
})
.catch((error) => {
setError(error);
});
} else {
setError("Please pass url as an argument");
}
}, [url]);
return [data, loading, error];
};
export default useFetch;
Explanation
We are creating a hook to help us fetch data and show us its loading state and error.
First, we create a state with react useState to hold the data, loading, and error state. Since we want to fetch data on the initial render, we use the react built-in useEffect and pass a dependency so it only runs when the dependency changes. In our case, it is the URL.
Remember the URL needs to be dynamic hence, we need to pass it as a prop in the useFetch component. Then we write our code in the useEffect code block.
We are checking to see if there is a URL. if none we update the state of the error.
if there is a URL, we set the loading to true.
We fetch our data using fetch or axios.
After fetching the data, we update the data and set the loading state to false.
We also set the error to the error message from the API should the be an error during the fetch request.
We return the data in an array format.
Now let's use the custom hook we just created. In our App.js file, paste the following.
import useFetch from "./hooks/useFetch";
import "./styles.css";
export default function App() {
const url = "https://jsonplaceholder.typicode.com/posts";
const [data, loading, error] = useFetch(url);
return (
<div className="App">
<h1>Power of React Custom Hook</h1>
{loading && <p>Loading data...</p>}
{error && <p>{error}</p>}
{data && (
<div>
{data.map((item, index) => (
<p key={index}>{item.title}</p>
))}
</div>
)}
</div>
);
}
Explanation
We create a react component
We import our custom hook
We pass our URL into our custom hook as an argument
We destructure out the value we sent from the useFetch hook
We use it where needed
Vuala!!! Congratulations, you now know how to create and use a custom hook.
Reference code: react-custom-hook
Top comments (0)