Kush's Blog

Kush's Blog

Top React Hook libraries

Top React Hook libraries

What are React Hooks?

Hooks provide a medium for passing state and properties without having to create class components.

Adopting a function-based approach, with Hooks we can separate our logic from our UI such that it can be reused in other parts of our application as well. In this article I have mentioned some of the top React Hook Libraries.

use-http

use-http is an incredibly useful package that is used as a replacement for Fetch API. Written and maintained with high quality.

It makes your coding much simpler and understandable, more precisely the data consumption part.

The hook itself uses TypeScript and even has support for SSR and GraphQL. It returns a response, loading, error data and different request methods such as Get, Post, Put, Patch and Delete.

Main features it provides are:

  • Request/Response interceptors
  • Suspense (experimental currently)
  • Retry functionality
  • Caching
import useFetch from "use-http"

const Example = () => {
  const [todos, setTodos] = useState([])
  const { get, post, response, loading, error } = useFetch("https://example.com")

  useEffect(() => { get("/todos") }, [])

  const addTodo = async () => {
      await post("/todos", { title: "example todo" });
      if (response.ok) setTodos([...todos, newTodo])
  }

  return (
    <>
      <button onClick={addTodo}>Add Todo</button>
      {error && 'Error!'}
      {loading && 'Loading...'}
      {todos.map(todo => (
        <span key={todo.id}>{todo.title}</span>
      )}
    </>
  );
};

useHover

useHover is a React state hook which determines if a React element is being hovered. Easy and intuitive to use.

The library is small, and simple to use, but can be powerful if you’re creative enough.

import useHover from "react-use-hover";

const Example = () => {
  const [isHovering, hoverProps] = useHover();
  return (
    <>
      <span {...hoverProps} aria-describedby="overlay">Hover me</span>
      {isHovering ? <div> I’m a little tooltip! </div> : null}
    </>
  );
}

React router hooks

React router is one of the most popular libraries for React. It is used for routing and getting the app URL history etc. Along with Redux it has implemented its hooks for getting such useful data.

Hooks offered are:

useHistory useLocation useParams useRouteMatch

UseHistory will get the data of the app’s history and methods such as push which pushes to a new route.

UseLocation will return the object that represents the current URL.

UseParams will return an object of key-value pairs of URL params of the current route.

UseRouteMatch will attempt to match the current URL with the given one which can be a string or an object of different options.

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

const Example = () => {
let history = useHistory();
let location = useLoction();
let isMatchingURL = useRouteMatch("/post/11");

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

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

Constate

It is a hook package that provides lifting local state up to React Context. It means that any state from any component can be easily lifted to the context with minimum effort.

This is useful in cases where you would like to use the same state in multiple spots, or provide the same state to multiple components.

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>
  );

React hook form

React hook form is a form hook library which is similar to Formik and Redux. With its much simpler syntax, speed, less rerenders and better maintainability it started to climb the GitHub ladders. The library offers even its form builder which is great.

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

function App() {
  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 required field."</span>}
      <input name="age" ref={register({ required: true })} />
      {errors.age && <span>"Please enter number for age."</span>}
      <input type="submit" />
    </form>
  );
}

useDebounce

useDebounce represents a small hook which is used for debouncing. It is used to postpone function execution to a later time. Often used in inputs and forms which fetch data.

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

export default function Input() {
  const [text, setText] = useState("Hello");
  const [value] = useDebounce(text, 1000);

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

usePortal

usePortal makes the creation of dropdowns, modals, notification popups, tooltips and much more, super easy. It provides creating elements outside the DOM hierarchy of the App.

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

const Example = () => {
    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>
          )}
       </>
 )
}

Interested in reading more such articles from Kushagra Sharma?

Support the author by donating an amount of your choice.