Using custom Hooks for code reusability
We have extensively discussed some of the in-built Hooks in React. Hooks have been part of the core React library since v16.8, which allows React components to exhibit statefulness without a class-based approach. Hooks such as useState
, useEffect
, UseMemo
, useRef
, useContext
, and useCallback
are specific functions to manage state, share stateful logic, and allow other interactions with React core APIs.
Now let’s understand what a custom Hook is and the benefits we can get from using them.
Custom Hooks are normal JavaScript functions whose name starts with use
and that usually invoke one or more in-built React Hooks. For instance, custom Hooks could be named anything as long as it starts with use, for instance, useCustomHook
, useFetchSpeakers
, or useUpdateDatabase
. Conventionally, there must be use
in front of your custom Hook name.
So why should you want to build your own custom Hooks? Let’s examine some of the reasons...