My Top 5 Custom React Hooks for your Web App

Ritesh Kumar
Frontend Weekly
Published in
3 min readApr 1, 2020

Why React Hook?

Many times, you would have faced the clutter of unrelated logic inside your React component if you have built the react apps earlier using class components.

In many cases, you might not be able to break the component into smaller pieces due to state logic spread all over the component. It will be harder to write test cases.

To solve these problems react has introduced some manageable functions which let you split one component into smaller functions. It will allow you to write the reusable functional components without using class components.

Hooks let you use more of React’s features without classes.

What is Hook?

A Hook is a special function that lets you “hook into” React features. For example, useState is a Hook that lets you add React state to function components.

When should you use a Hook?

If you have a functional component and you need to add some state to it, previously you had to convert it to a class component. Now, with the introduction of React Hooks in React 16.8, you can now use a Hook inside the existing functional component to achieve the desired state.

Normally, variables “disappear” when the function exits but state variables are preserved by React.

Custom Hooks

Custom hooks leverage the power of React hooks to add additional functionality to our React apps.

1. use-mouse-action

React Hooks to listen to both mouse down or up and click events with a once called function.

This library provides three React Hooks:

  • useMouseAction
  • useMouseDown
  • useMouseUp

They all want the same parameter: either the callback function or an options object with the callback function in the onAction parameter.

They all return an object of event listeners to add on the element.

2. @rehooks/online-status

React hook for subscribing to online/offline events and the navigator.onLine property to see current status

3. react-use-idb

React side-effect hook that manages a single indexDB item. A drop-in replacement over useLocalStorage. We rely on indexDB for structural cloning which is not supported in local storage.

4. react-script-hook

React hook to dynamically load an external script and know when its loaded.

5. react-window-communication-hook

React hook to communicate among browsers contexts (windows, tabs, iframes).

Example use case: When the user presses logout in one tab, logout from every other tab.

References:

--

--

Ritesh Kumar
Frontend Weekly

SMTS Frontend @ Nutanix | MBA Product Mgmt. | IIT Grad(B.Tech) | 1 U.S Patent