DEV Community

loading...
Cover image for Top 10 React Hooks Library

Top 10 React Hooks Library

kpiteng
CEO w KPITENG | Digital Transformation | Web, Mobile, AR/VR, AI/ML, Blockchain App Development | UI/UX Design, IoT Solutions In India, USA
Updated on ・5 min read

Hooks make developers' life easy by helping in writing fewer lines of code, clean code, more readable, maintainable, reusable code. Many popular libraries now offer Hooks, let’s check some of them today.

1. use-http

use-http is a popular package that is used as a replacement for Fetch API. It's a well maintained library and easy to integrate in a few lines of code. Hooks written in TypeScript and support Server Side Rendering (SSR) and GraphQL. It returns a response, loading, error data and work with different request methods, Get, Post, Put, Patch and Delete.

Features -

  • Request/Response Interceptors
  • Abort/Cancel pending http requests on component unmount
  • Retry Functionality
  • Build-in Caching
  • TypeScript Support

It’s nicely documented with both CodeSanbox Examples and Youtube Videos in GitHub readme.

Installation - npm i use-http

Integration -

import React, { useEffect, useState } from 'react';
import useFetch from 'use-http'

function UseHTTPExample() {
  const [todos, setTodos] = useState([])
  const { get, post, response, loading, error } = useFetch('https://jsonplaceholder.typicode.com')

  useEffect(() => { initializeTodos() }, []);

  async function initializeTodos() {
    const initialTodos = await get('/todos')
    if (response.ok) setTodos(initialTodos)
  }

  async function addTodo() {
    const newTodo = await post('/todos', { title: 'KPITENG Article Writting' })
    if (response.ok) setTodos([newTodo, ...todos])
  }

  return (
    <>
      <button onClick={addTodo}>Add Todo</button>
      {error && 'Error!'}
      {loading && 'Loading...'}
      {todos.map(todo => (
        <div key={todo.id}>{todo.title}</div>
      ))}
    </>
  )
}
export default UseHTTPExample;
Enter fullscreen mode Exit fullscreen mode

2. Redux Hooks

Redux is a most popular state management library, most of all already using Redux. Redux Hooks offers an alternative to HOC (Higher Order Component) pattern with the existing connect() method. Redux Hooks made a simple way to connect to store, fetch data, and dispatch action. Let’s see it.

Popular Redux Hooks -

  • useSelector
  • useDispatch
  • useStore

Installation - npm i react-redux @types/react-redux

Integration -

import { useSelector, useDispatch } from "react-redux";
import React from "react";
import * as actions from "./actions";

const ReduxHooksExample = () => {
  const dispatch = useDispatch();
  const counter = useSelector((state) => state.counter);

  return (
    <div>
      <span>{counter.value}</span>
      <button onClick={() => dispatch(actions.incrementCounter)}>
        Counter +1
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

3. useMedia

Have you ever faced the issue of managing CSS media query? useMedia hook simplified this problem in a line of code. It's a sensory hook which tracks the state of CSS media query and helps you to design & develop responsiveness apps.

useMedia package written in TypeScript. Package has a well-structured documentation which explains usage and testing methods.

Installation - npm i use-media

Integration -

const ResponsiveComponent = () => {
    const isWide = useMedia({ minWidth: "1000px" });

    return (
      <span>
        Screen is wide: {isWide ? "It's WideScreen" : "It's NarrowScreen"}
      </span>
    );
  };
Enter fullscreen mode Exit fullscreen mode

4. React Hook Form

React Hook Form is form hooks library, it’s similar to Formik and Redux Form, but much simpler, faster, less re-rendering. useForm returns register, handleSubmit, errors, register help to register element, handleSubmit manage submit action, errors help to manage validation and showing element input errors.

Installation - npm i react-hook-form

Integration -

import React from "react";
import { useForm } from "react-hook-form";

function SignUpComponent() {
  const { register, handleSubmit, errors } = useForm();
  const onSubmit = (data) => {
    // logs {firstName:"exampleFirstName", lastName:"exampleLastName"}
    console.log(data);
  };

  return (
    <form onSubmit={handleSubmit(onSubmit)}>
      <input name="firstName" ref={register} />
      <input name="lastName" ref={register({ required: true })} />
      {errors.lastName && <span>"Last name is a mandatory field."</span>}
      <input name="age" ref={register({ required: true })} />
      {errors.age && <span>"Please enter number for age."</span>}
      <input type="submit" />
    </form>
  );
}
Enter fullscreen mode Exit fullscreen mode

5. Constate

Constate hook provides lifting local state to React Context Level. So you can access/update state variables anywhere in the application with few lines of code. This is useful when you use the same state in multiple components. For example, you have Themes, Colors, Fonts used in multiple components, Users are allowed to change at one place and it should be reflected in the whole application. Package written in TypeScript and very compact.

Installation - npm i constate

Integration -

import React, { useState } from "react";
import constate from "constate";

// custom hook
function useCounter() {
  const [count, setCount] = useState(0);
  const increment = () => setCount(prevCount => prevCount + 1);
  return { count, increment };
}

// hook passed in constate
const [CounterProvider, useCounterContext] = constate(useCounter);

function Button() {
  // use the context
  const { increment } = useCounterContext();
  return <button onClick={increment}>+</button>;
}

function Count() {
  // use the context
  const { count } = useCounterContext();
  return <span>{count}</span>;
}

function App() {
  // wrap the component with provider
  return (
    <CounterProvider>
      <Count />
      <Button />
    </CounterProvider>
  );
Enter fullscreen mode Exit fullscreen mode

6. useDebounce

useDebounce hooks - it’s name represents - used for debouncing. It is used to postpone execution to a later time like setTimeout in React Native.

Installation - npm i use-debounce

Integration -

import React, { useState } from "react";
import { useDebounce } from "use-debounce";

export default function UseDebounceExample() {
  const [text, setText] = useState("Hello KPITENG");
  const [value] = useDebounce(text, 3);

  return (
    <div>
      <input
        defaultValue={"Hello"}
        onChange={(e) => {
          setText(e.target.value);
        }}
      />
      <p>Value: {text}</p>
      <p>Debounced value: {value}</p>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

7. React Router Hooks

React Router is a popular library for component routing, component history management, and many more.

Popular Router Hooks -

  • useHistory
  • useLoaction
  • useParams
  • useRouteMatch

useHistory helps developers to manage component navigation history. useLocation returns the object that represents the current URL to manage your URL based use cases. useParams returns the arguments (parameters) sent while routing between components. useRouteMatch will match currentURL with a given string to perform a use case.

Installation - npm i react-router-dom

Integration -

import { useHistory, useLocation, useRouteMatch } from "react-router-dom";

const RouteExample = () => {
  let history = useHistory();
  let location = useLocation();
  let isMatchingURL = useRouteMatch("/blog/33");

  function handleClick() {
    history.push("/home");
  }

  return (
    <div>
      <span>Current URL: {location.pathname}</span>
      {isMatchingURL ? <span>Matching provided URL! </span> : null}
      <button type="button" onClick={handleClick}>
        Go home
      </button>
    </div>
  );
};
Enter fullscreen mode Exit fullscreen mode

8. useHover

useHover hooks identify react element if being hovered. It’s very easy to use and integrate. It also offers the delay of the hover effect. useHover supports TypeScript.

Installation - npm i react-use-hover

Integration -

import useHover from "react-use-hover";

const HoverExample = () => {
  const [isHovering, hoverProps] = useHover();
  return (
    <>
      <span {...hoverProps} aria-describedby="overlay">
        Hover me
      </span>
      {isHovering ? <div> Hey, you hover me! </div> : null}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

9. usePortal

usePortal hooks allow creation of elements outside the DOM hierarchy of the Application. usePortal widely used having dropdowns, notification popups, modals, tooltips. usePortal works with Server Side Rendering (SSR) as it is isomorphic. usePortal written in TypeScript. It allows customization of portal styling and many more options.

usePortal has a well defined Github readme with codesanbox example for each SSR, Modal, Dropdown, Tooltip.

Installation - npm i react-useportal

Integration -

import React, { useState } from "react";
import usePortal from "react-useportal";

const UsePortalExample = () => {
  const { ref, openPortal, closePortal, isOpen, Portal } = usePortal();

  return (
    <>
      <button ref={ref} onClick={() => openPortal()}>
        Open Portal
      </button>
      {isOpen && (
        <Portal>
          <p>
            This Portal handles its own state.{" "}
            <button onClick={closePortal}>Close me!</button>, hit ESC or click
            outside of me.
          </p>
        </Portal>
      )}
    </>
  );
};
Enter fullscreen mode Exit fullscreen mode

10. useLocalStorage

useStorage hook allows developers to extract and save data in localStorage. It automatically do JSON serialization and synchronization. useLocalStorage written in TypeScript so it offers types.

Installation - npm i @rehooks/local-storage

Integration -

import React, { useState } from "react";
import { writeStorage, useLocalStorage } from '@rehooks/local-storage';

const UseLocalStorageExample() {
  let counter = 0;
  const [counterValue] = useLocalStorage('counterValue');

  return (
    <div>
      <span>{counterValue}</span>
      <button onClick={() => writeStorage('i', ++counter)}>
        Click Me
      </button>
    </div>
  );
}
Enter fullscreen mode Exit fullscreen mode

Thanks for reading Blog!

KPITENG | DIGITAL TRANSFORMATION
www.kpiteng.com/blogs | hello@kpiteng.com
Connect | Follow Us On - Linkedin | Facebook | Instagram

Discussion (6)

Collapse
nasimuddin profile image
Nasim Uddin

Or just use react-use.
Life will be so much easier.

Collapse
primakurniawan profile image
Prima Tondy Arya Kurniawan

Wow the list is insane, i often cretae custome hook by my self, i didnt know there are so much there already we can use.

Collapse
sebastianzawolanski profile image
Sebastian • Edited

In last example you do not import useLocalStorage hook.

Collapse
manuelhpineda_87 profile image
Manuel Pineda

Damn I usually create custom hooks to do all this things myself!

Collapse
ravisojitra profile image
ravi

4th title should be react-hook-form not react-redux-form

Collapse
kpiteng profile image
kpiteng Author

Thanks, Corrected!