Custom Hooks in React

Shakya Peiris
1 min readMay 20, 2021

Hello everyone, hope you are doing well. Today let’s discuss how we could implement custom hooks in react. As we now in 2019 react hooks were introduced and it made our workflow easier. Hooks are regular JavaScript functions and there are some rules that we have to follow when we are using hooks,

  1. Hooks must start with ‘use.’
  2. Hooks can only use within functional components (not in regular functions or class based components)
  3. Hooks cannot be implemented within conditions. Therefor we have to implement conditions inside hooks like !response.ok condition used to find whether there is an error in the fetched data in useEffect hook.

etc.…

What are custom hooks?

Custom hooks are simply hooks developed by external parties. For example useDispatch and useSelector hooks come with react-redux library and they are considered to be custom hooks

How can we build custom hooks?

As I mentioned earlier all the hooks are functions. So we can simply build a function which returns some value/object /array after executing some code. Reffer the following custom http hook.

Hope you have learned something from this article. Make sure to subscribe me on YouTube. Thanks You

--

--