React hooks are a new feature published by react team in version 16.8, it's allow you to use the state and other react features.
In simple terms hooks are functions that connect react state and lifecycle features from the function components, don't forget react hooks only work in react functions.
Besides built-in Hooks such as( useState, useEffect, useCallbackâŚ), you can build your own hooks.
So what are custom hooks?đ§
Custom hooks are normal javaScript function that accepts arguments and return outputs but they contain stateful logic.
They are like other hooks so their name starts with 'use' and can be used to call other hooks, we use it in react function and we call it only in the top level of the component
Why and When to use React Custom Hooks?
We use it any time when we need to share a logic between different components.
Custom hooks give us some benefits:
- Reusability: we can use the same hook again and again, without the need to write it twice.
- Readability: separate logic from the component to a custom hook will make the component easier to read.
- Clean-code: Fix logic in one place (custom hooks) becomes easier than changing it in more than one.
let's see an example make simple API call using Axios
components/AllPosts.js
We send GET request using axios without any headers or body to fetch posts with response as result or error.
components/AddPost.js
Here we send POST request with headers and body of the post using axios.
Look at the previous examples, you can see that both components above have a very similar logic. They all call API ,The only difference is that they render different UI , different URL when calling API and different request method.
We can reduce the repetition by creating a custom hook for example useAxios() for reuse as follows:
src/hooks/useAxios.js
Here we made a reusable hook can accept an argument that contain the request details like (URL, request method, headers and body)
So let's modify our components
components/AllPosts.js
components/AddPost.js
Conclusion:
we have learned the importance of using custom hooks like saving time, make your code clean reusable and readable, also we have shown real examples from project with an explanation of when we used certain hooks.
Top comments (0)