DEV Community

Cover image for How to Create a Custom Hook in React
Anurag Gharat
Anurag Gharat

Posted on

How to Create a Custom Hook in React

In earlier React versions only Class based components allowed to use and manipulate state. With introduction of Hooks in React 16.8 you can now manage state operations in Functional Components as well.

What are React Hooks?

Hooks are nothing but functions starting with use. As the name suggests these functions ‘hook’ onto your components. These hooks are functions that manipulate state for you. React comes with default pre built hooks like useState, useEffect , useContext and lot more. Each hook has a unique purpose. Here in this blog we will learn how to create our own Custom hook.

Why to create your own Hook?

Lets say you have a component which has some logic. This logic is being used across all your application components. So instead of repeating the code in every component that uses this logic, you can create a Hook that performs that logic and hooks onto the components that need it.

Hence hooks allow you to reuse your logic across your application. This makes your code more readable, efficient and easy to maintain.

Creating custom Hook

Lets create a fresh react application. Open your terminal and paste the following command.

npx create-react-app customhooks
Enter fullscreen mode Exit fullscreen mode

This will create a new React application for us.

For tutorial purpose we will create small application that fetches post from a remote API and shows the title of the posts on home page. We will use the Rest API provided by JSON placeholder. Here it the link for it.

First we will fetch the data without a custom hook. Clean up your App.js file and add the following code. We have created 3 states. Data to store data, loading to show loading state and Error to show errors. This is how usually people fetch data in React. We used useEffect hook to fetch data as soon as the component is loaded.

import { useEffect, useState } from 'react';
import './App.css';

function App() {

  const [data,setData] =useState(null)
  const [loading, setloading] = useState(false);
  const [error, setError] = useState(false);

  const fetchData=async()=>{
    setloading(true)
    try {
       const res = await fetch("https://jsonplaceholder.typicode.com/posts");
       const resdata = await res.json();
       setData(resdata);
    } catch (error) {
      setError(error)
    }finally{
      setloading(false)
    }
  }

  useEffect(()=>{
    fetchData();
  },[])

  return (
    <div className="App">
      <h1>Custom Hooks in React JS</h1>
      {loading && <h1>Loading</h1>}
      {error && <h1>Something went wrong</h1>}
      {data && data.map(item=>(<p key={item.id}>{item.title}</p>))}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Run the application using npm start command and the output should be similar to this.

Output

Now we will create a Custom hook named useFetch that will fetch data for us. We will pass URL to the hook and the hook will return us data, error and loading state. Since we pass URL as a parameter we can reuse this hook in every component where we want to fetch data from a Rest API.

I created a Hooks directory and made a JS file with the name useFetch . This is where all our custom hook code data should go.

Folder Structure

💡 Custom hooks should always start with ‘use’.

Now we will take the code from our App.js file and put it in the useFetch.js file. Here is final code of useFetch.js .

import { useEffect, useState } from "react";

export function useFetch(url) {
    const [data, setData] = useState(null);
    const [loading, setloading] = useState(false);
    const [error, setError] = useState(false);

const fetchData = async () => {
  setloading(true);
  try {
    const res = await fetch(url);
    const resdata = await res.json();
    setData(resdata);
  } catch (error) {
    setError(error);
  } finally {
    setloading(false);
  }
};

   useEffect(() => {
     fetchData();
   }, []);

  return [data,loading,error]
}
Enter fullscreen mode Exit fullscreen mode

After completing our hooks lets remove the unwanted code from App.js file and call the useFetch.js hook. We pass the URL as a parameter to the hook.

import './App.css';
import { useFetch } from './Hooks/useFetch';

function App() {

  const [data, loading, error] = useFetch(
    "https://jsonplaceholder.typicode.com/posts"
  ); 

  return (
    <div className="App">
      <h1>Custom Hooks in React JS</h1>
      {loading && <h1>Loading</h1>}
      {error && <h1>Something went wrong</h1>}
      {data && data.map(item=>(<p key={item.id}>{item.title}</p>))}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Now again run the application and it should show the same output as it showed it earlier.

Final Output

That’s for the blog. We saw how to create a Custom Hook. Similar to this you can create even more hooks that perform tasks which are repeated across your components.

Thank you for reading! If you loved the blog, do like it and share it. I post many such tweets about Web Development and Programming on Twitter, you can follow me if you love such content! Thanks!

Top comments (2)

Collapse
 
vidhanshu profile image
vidhanshu borade

thank you

Collapse
 
vidhanshu profile image
vidhanshu borade

*thank you *