Top 10 React Hooks Library

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

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;

2. Redux Hooks

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

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

4. React Hook Form

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

5. Constate

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

6. useDebounce

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

7. React Router Hooks

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

8. useHover

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

9. usePortal

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

10. useLocalStorage

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

Thanks for reading Blog!

KPITENG | DIGITAL TRANSFORMATION
www.kpiteng.com/blogs | [email protected]
Connect | Follow Us On - Linkedin | Facebook | Instagram

22