DEV Community

Cover image for A guide to create custom hooks in React
Ashish Prajapati
Ashish Prajapati

Posted on

A guide to create custom hooks in React

First of all before creating any custom hook, we should understand what are hooks and why they are needed. So I would suggest reading my previous blog here link.


Table of content


Creating our first custom hook

  • To create our first custom hook, just create a simple javascript function with use prefix. It is case sensitive, so do write exactly as it is. For example just name it like useFetch or useTodo or maybe useDelete, whatever you can think of. Be clear of what name you are giving it and the name should represent what it's doing.
function useEvent(){ useEffect(() => { console.log('effect') },[]) } 
Enter fullscreen mode Exit fullscreen mode

That's it!!


Encapsulating reusable logic into Custom hook

  • You can make best out of your custom hook by encapsulating the same logic that has been used across in your React application within custom hook. For example, it can be fetch logic for getting same data in your application or it can be logic for getting the current theme status(dark or light or something else).

Creating a real life custom hook

  • Below is the fetch hook example, which is very simple implementation of what an advanced level hook can handle. It handles these things internally:-
    • Fetching data based on the given url prop on initial mount
    • Handling the error and loading status while data fetching
    • Returns the given data which we are using in App component
function useFetch(url: string){ const [data, setData] = useState<any>(null) const [status, setStatus] = useState<"fetching"|"error"|"fetched">("fetching") useEffect(()=>{ fetch(url) .then((res)=> res.json()) .then((res)=> { setData(res) setStatus("fetched") }) .catch(err=> setStatus("error")) },[]) return {data, status} } function App(){ const {data,status} = useFetch("https://fakestoreapi.com/products") if(status == "fetching"){ return ( <div>loading...</div> ) } if(status == "error" && !data){ return ( <div>error while fetching the data</div> ) } return ( <div>{JSON.stringify(data)}</div> ) } 
Enter fullscreen mode Exit fullscreen mode

What we learned

With hooks, you can take away your most of your boilterplate code or logic into the custom hooks and use those hooks in the application.

  • It helps you to write DRY code.
  • Simple and easy to create.
  • Encapsulate the common logic of the application

Top comments (0)