Digital Transformation in HealthCare Solution

Tech Talk

Top 10 React Hooks Library

19 JUNE 2021

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;

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

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

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

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

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

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

8. useHover Hooks

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

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

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

Thanks for reading Blog!

Want to receive Tech Articles!

Get tech aricles directly in your inbox! Share your email with us and receive tech articles as instant as we publish!

KPIENG

KPITENG

DIGITAL TRANSFORMATION

Want to talk about your project?

  • INDUSTRY
  • E-Commerce & Shopping
  • Healthcared & Fitness
  • Banking & Finance
  • Education
  • Logistics & Distribution
  • Social Networking
  • Real Estate
  • Food & Restaurant
  • On-Demand Services
  • Media
  • IT & Telecom
  • Productivity

Want to talk about your project?

© 2021 KPITENG, all rights reserved