Top 10 React Hook libraries

Top 10 React Hook libraries:

 

https://ift.tt/2UgvLrq

Hooks came and took the React community by the storm. It’s been a while since their initial release, meaning there are a lot of supporting libraries. It is hard not to come by “hooks” word while searching for anything related to React. If you haven’t already, you should pick them up into your codebase as soon as possible. They will make your coding life much easier and enjoyable.

Keeping clean code style, readability, maintainability, fewer lines of code as well as reusability is crucial in the React development. This blog will present to you the top 10 React Hook libraries which you should start using immediately. Without further delay let’s get on the way.

1. 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

It is well documented with both CodeSandbox examples and Youtube videos together with GitHub readme.

Usage example:

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 (
    
      Add Todo
      {error && 'Error!'}
      {loading && 'Loading...'}
      {todos.map(todo => (
        {todo.title}
      )}
    
  );
};
Enter fullscreen mode Exit fullscreen mode

2. useMedia

Have you ever needed a way of tracking the CSS media query? The useMedia hook provides a simplistic approach to the problem. It is a sensory hook which tracks exactly that. Media queries are really important as well as the responsiveness of any app or website.

Written in TypeScript it offers its support. The package has well-defined documentation which explains the usage as well as the testing methods for the hook.

Usage example:

import useMedia from 'use-media';

const Example = () => {
  const isWide = useMedia({minWidth: '1000px'});

  return (
    
      Screen is wide: {isWide ? "WideScreen" : "NarrowScreen"}
    
  );
};
Enter fullscreen mode Exit fullscreen mode

3. Constate

Constate 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. The name comes from a wordplay merging Context and State.
Written in Typescript and very small in size. The documentation is not so detailed, but it gets the job done.

Usage example:

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

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

function App() {
  // wrap the component with provider
  return (
    
      
      
    
  );
Enter fullscreen mode Exit fullscreen mode

4. Redux hooks

Redux is a well-known tool for many, if not all, React developers. It is used as a global state manager throughout the application. It went onboard with hooks a couple of months after the React’s initial release. It offers an alternative to the HOC (Higher Order Component) pattern with existing connect() method.

Most notable hooks provided are:

  • useSelector
  • useDispatch
  • useStore

The documentation is quite good, a bit complex but it will provide you with any information needed to start using them.

Usage example:

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

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

return (
{counter.value} dispatch(actions.incrementCounter)}> Counter +1
); };
Enter fullscreen mode Exit fullscreen mode

5. React hook form

React hook form is a form hook library which is similar to Formik and Redux form, but better! With its much simpler syntax, speed, less rerenders and better maintainability it started to climb the GitHub ladders.
It is tiny in size and built with performance in mind. The library offers even its form builder which is great! It has one of the biggest amounts of GitHub starts for a React hooks library, 14.8k.

Usage example:

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 (
    
      
      
      {errors.lastName && "Last name is a required field."}
      
      {errors.age && "Please enter number for age."}
      
    
  );
}
Enter fullscreen mode Exit fullscreen mode

6. 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.

Usage example:

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 (
    
{ setText(e.target.value); }} />

Value: {text}

Debounced value: {value}

); }
Enter fullscreen mode Exit fullscreen mode

7. useLocalStorage

useLocalStorage is a small hook just like the one above. It is really useful for extracting and setting the data inside localStorage. Manipulation is made easy.
Offers automatic JSON serialization and synchronisation across multiple tabs and is written in TypeScript so it offers types.

Documentation is written in a quality manner and is quite understandable with extended examples.

Usage example:

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

export default function Example() {
  let counter = 0;
  const [counterValue] = useLocalStorage('counterValue');

  return (
    
{counterValue} writeStorage('i', ++counter)}> Click Me
); }
Enter fullscreen mode Exit fullscreen mode

8. 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 (See how Portals work here). 
The hook works with SSR as it is isomorphic. Written in TypeScript and has built-in state. It also offers the full customization of the portal styling and ton of other options.

Documentation written for it is quite good shows many examples which will be more than enough to start using the library/hook yourself.

Usage example:

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

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

    return (
      
          openPortal()}>
            Open Portal
         
          {isOpen && (
            
              

This Portal handles its own state.{' '} Close me!, hit ESC or click outside of me.

)} ) }
Enter fullscreen mode Exit fullscreen mode

9. 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.

It offers the delay of the hover effect as well. TypeScript supported. Documentation is not as detailed, but it will show you how to use it fairly.

Usage example:

import useHover from "react-use-hover";

const Example = () => {
  const [isHovering, hoverProps] = useHover();
  return (
    
      Hover me
      {isHovering ? 
I’m a little tooltip!
: null} ); }
Enter fullscreen mode Exit fullscreen mode

10. 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

Its names are pretty self-explanatory. 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. Finally, useRouteMatch will attempt to match the current URL with the given one which can be a string or an object of different options.

Documentation is good and written with many examples

Usage example:

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 (
    
Current URL: {location.pathname} {isMatchingURL ? Matching provided URL! Yay! : null} Go home
); }
Enter fullscreen mode Exit fullscreen mode

There are much more hook libraries out there, but these are the ones I’ve decided to talk about. Please try them out, I promise you won’t regret it. If you do happen to like them a lot, go and support them in any way. The hooks are still relatively a new way of doing this, but they are here to stay. In further months we expect even more brilliant libraries and hook examples to jump up to the surface.

Hope you have found this post interesting, and that you have learned something new. Have fun in your further exploration of the hooks! Happy developing.

https://ift.tt/2UgvLrq

from Tumblr https://generouspiratequeen.tumblr.com/post/632504996254171136

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s