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

Create your custom hook

01 | Fetch and assign in the component

First case — We fetch data and assign it to a local state
Fetched data are well displayed

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<something>)

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 :



Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store