Creating Reusable Custom React Hooks

Noopur Chhajed
3 min readMay 7, 2021

In this article, we will try to develop our own custom hook & try to understand the whole logic behind it. Before we start with creating custom hook you must be aware of hooks.

Quick Introduction to Hooks

Hooks are a new edition in React 16.8. They are basically functions that help you to manage state, use React lifestyle & other features in functional components. React provides us with 10 hooks.
1. useEffect
2. useState
3. useContext
4. useReducer
5. useCallback
6. useMemo
7. useRef
8. useImperativeHandle
9. useLayoutEffect
10. useDebugVaue
Discussing each hook is out of scope for this article.

In simple words, React Hooks are just functions that take arguments and return value.

Rules of Hooks
1. Only call hooks at top level —
Do not call hooks inside loops, conditions or nested functions. Always call it at the top level of react function.
2. Only call hooks from function components- Do not call hooks from regular javascript functions. Call from react function components or custom hooks.

Creating modal toggle function using React hooks
Suppose you want to toggle the modal on button click. Imagine having 5 modals for 5 different components. Every time you need to write toggle functionality to toggle modal. But thanks to react hooks that provide us with ability to write reusable functions amongst components. Let’s get started….!!

1. Create a new file as use-toggle.js

2. Implementing the custom hook logic.

  • This useToggle hooks accept one argument:
    initialMode — This argument depicts the open/close behaviour of modal. Initially the modal is closed.
  • Here we use the useState Hook to manage the state (open,close) of modal. For example: const [toggleOpen, setToggle] = React.useState(initialMode).
  • The logic is pretty simple: toggle functions perform the logical reversal operation. If something was true it will set to false and vice versa.

3. Using custom hook in our component:

Creating simple modal component
1. Creating Modal component Modal.js file.

Modal.js

2. Adding style to your modal component. Update Modal.css

Modal.css

3. Then update your App.js

App.js

And you are good to go…!!

Final Result

Modal

Advantages of Custom Hooks

  • Hooks allows us to create reusable, isolated components and easily share logic across components to avoid redundancy.
  • Hooks don’t create another element in DOM like HOC’S do.
  • Custom Hooks involves less lines of code & hence easy to test & maintain.
  • With the help of hooks, you don’t have to refactor a functional component into a class component when it grows.
  • With hooks you don’t need to use ‘this’ keyword.

Conclusion
With this article, it is very clear that hooks encourage the use of functional components to benefit from its simplicity and efficiency. It focuses on reusing stateful logics amongst components.

--

--