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
01 | Fetch and assign in the component
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:
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 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 **! ✅
Let’s use it in our application to retrieve and display the data !
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 :