DEV Community

Cover image for Create your first custom hook with React
horhorou
horhorou

Posted on

Create your first custom hook with React

Creating custom hooks can quickly make your application lighter in architecture and clearer in code for yourself and others developers.

Today we will see how to create your own custom hook to retrieve data from a to-do list from the https://jsonplaceholder.typicode.com

Create your first hook with me

01 | Fetch and assign in the component

First case — We fetch data and assign it to a local state

It works, we can see the items

This method works very well, and this may be how you are used to doing it.
On the other hand, it becomes very quickly unmanageable as soon as you have to retrieve several different data

Let’s see how to improve our code

02 | Create a custom hook

Let’s start by creating a new .js file in a new folder called hooks.

This file will be named** useTodos.js**
(Note the naming convention for custom hooks, they all start with use)

In a second step, let’s start by creating the data fetching method inside that file:

A async/await method to fetch the placeholder data

Then we can create a new constant that we will name like the file: useTodos

This method will have a local state that will be returned **to the different components when you call **useTodos

We have now a todos state that is an empty array

We can now call our fetchTodos method in a useEffect method **and assign the data to the **todos state through setTodos

We just need to return the todos state and it’s…** DONE **! ✅

Well done ! 👏

Let’s use it in our application to retrieve and display the data !

One variable called todos and our custom hook in action !


Well done!
What you need to remember is that :

A hook is a simple function that takes care of a logical block separately from your component and returns only the essential of what you really want

Source code on my Github :
https://github.com/horhorou/create-first-hook

Discussion (0)