Best 6 Useful React Hooks You Should Know

Best 6 Useful React Hooks You Should Know

Did you know there are thousands of useful React Hooks that you can start using today? In this post, you'll know best 6 useful React Hooks you should Have in Your Toolbox

According to the React documentation:

Hooks are functions that let you “hook into” React state and lifecycle features from function components. Hooks don’t work inside classes — they let you use React without classes. (We don’t recommend rewriting your existing components overnight but you can start using Hooks in the new ones if you’d like.) React provides a few built-in Hooks like useState. You can also create your own Hooks to reuse stateful behavior between different components

Here are five handy React Hooks you can start using today.

Without further ado, here are five React Hooks that you can start using today in your React project.

@rehooks/component-size

@rehooks/component-size is a React Hook for determining the size of a component. It’s useful when it comes to responsive images and components that need a rerender when resizing.

Installing

yarn add @rehooks/component-size

Usage

import { useRef } from 'react'
import useComponentSize from '@rehooks/component-size'function MyComponent() {
  let ref = useRef(null)
  let size = useComponentSize(ref)
  // size == { width: 100, height: 200 }
  let { width, height } = size
  let imgUrl = `https://via.placeholder.com/${width}x${height}`  return (
    <div style={{ width: '100%', height: '100%' }}>
      <img ref={ref} src={imgUrl} />
    </div>
  )
}

Note: ResizeObserver is the API used to determine if an element is resized. Browser support is pretty good in Chrome but is still missing support in other major browsers.

@rehooks/window-scroll-position

@rehooks/window-scroll-position is a React Hook for determining the window-scroll position. It’s useful when you want to animate objects based on whether and where the user is scrolling.

Installing

yarn add @rehooks/window-scroll-position

Usage

import useWindowScrollPosition from '@rehooks/window-scroll-position'function MyComponent() {
  // optionally you can pass options, those are default:
  let options = {
    throttle: 100,
  }
  let position = useWindowScrollPosition(options)
  // position == { x: 0, y: 0 }
  return <div />
}

@rehooks/local-storage

@rehooks/local-storage is a React Hook for enabling synchronization with local-storage.

Installing

Yarn

yarn add @rehooks/local-storage

NPM

npm i @rehooks/local-storage

Usage

writeStorage: This can be anywhere from within your application.

import React from 'react';
import { writeStorage } from '@rehooks/local-storage';let counter = 0;const MyButton = () => (
  <button onClick={_ => writeStorage('i', ++counter)}>
    Click Me
  </button>
);

useLocalStorage: This component will receive updates to itself from local storage.

import React from 'react';
import { useLocalStorage } from '@rehooks/local-storage';function MyComponent() {
  const [counterValue] = useLocalStorage('i'); // send the key to be tracked.
  return (
    <div>
      <h1>{counterValue}</h1>
    </div>
  );
}

deleteFromStorage: You may also delete items from the local storage as well.

import { writeStorage, deleteFromStorage } from '@rehooks/local-storage';writeStorage('name', 'Homer Simpson'); // Add an item firstdeleteFromStorage('name'); // Deletes the itemconst thisIsNull = localStorage.getItem('name'); // This is indeed null

Full example

import React from 'react';
import ReactDOM from 'react-dom';
import { writeStorage, deleteFromStorage, useLocalStorage } from '@rehooks/local-storage';const startingNum = 0;const App = () => {
  const [getNum, setNum] = useLocalStorage('num');  return (
    <>
      <p>{getNum}</p>
      <button onClick={_ => setNum(getNum ? getNum + 1 : 0)}>Increment</button>
      <button onClick={_ => deleteFromStorage('num')}>Delete</button>
    </>
  );
};// Assuming there is a div in index.html with an ID of 'root'
ReactDOM.render(<App />, document.getElementById('root'));

The @rehooks/local-storage API docs can be found here.

react-use-form-state

Managing form state in React can be a bit unwieldy sometimes. There are plenty of great solutions already available that make managing form states a breeze. However, many of those solutions are opinionated, packed with tons of features that may end up not being used, and/or require shipping a few extra bytes.

Luckily, the recent introduction of React Hooks and the ability to write custom Hooks have enabled new possibilities when it comes to sharing state logic. Form state is no exception.

react-use-form-state is a small React Hook that attempts to simplify managing form state, using the native form input elements you are familiar with.

Getting started

To get it started, add react-use-form-state to your project:

npm install --save react-use-form-state

Note that react-use-form-state requires [email protected]^16.8.0 as a peer dependency.

Basic usage

import { useFormState } from 'react-use-form-state';export default function SignUpForm({ onSubmit }) {
  const [formState, { text, email, password, radio }] = useFormState();  function handleSubmit(e) {
    // ...
  }  return (
    <form onSubmit={handleSubmit}>
      <input {...text('name')} />
      <input {...email('email')} required />
      <input {...password('password')} required minLength="8" />
      <input {...radio('plan', 'free')} />
      <input {...radio('plan', 'premium')} />
    </form>
  );
}

From the example above, as the user fills in the form, the formState object will look something like this:

{
  values: {
    name: 'Mary Poppins',
    email: '[email protected]',
    password: '1234',
    plan: 'free',
  },
  touched: {
    name: true,
    email: true,
    password: true,
    plan: true,
  },
  validity: {
    name: true,
    email: true,
    password: false,
    plan: true,
  },
  errors: {
    password: 'Please lengthen this text to 8 characters or more',
  },
  clear: Function,
  clearField: Function,
  reset: Function,
  resetField: Function,
  setField: Function,
}

Initial state

useFormState takes an initial state object with keys matching the names of the inputs.

export default function RentCarForm() {
  const [formState, { checkbox, radio, select }] = useFormState({
    trip: 'roundtrip',
    type: ['sedan', 'suv', 'van'],
  });
  return (
    <form>
      <select {...select('trip')}>
        <option value="roundtrip">Same Drop-off</option>
        <option value="oneway">Different Drop-off</option>
      </select>
      <input {...checkbox('type', 'sedan')} />
      <input {...checkbox('type', 'suv')} />
      <input {...checkbox('type', 'van')} />
      <button>Submit</button>
    </form>
  );
}

Check out the API documentation section for an in-depth dive.

react-fetch-hook

react-fetch-hook is a React Hook for conveniently using the Fetch API. The package includes the following:

  • Tiny (397B) — calculated by size-limit
  • Both Flow and TypeScript types included

Getting started

Yarn

yarn add react-fetch-hook

NPM

npm i react-fetch-hook --save

Usage

import React from "react";
import useFetch from "react-fetch-hook";

const Component = () => {
  const { isLoading, data } = useFetch("https://swapi.co/api/people/1");

  return isLoading ? (
    <div>Loading...</div>
  ) : (
    <UserProfile {...data} />
  );
};

useFetch accepts the same arguments as the fetch function.

Custom formatter

The default is the response => response.json() formatter. You can pass the custom formatter like this:

const { isLoading, data } = useFetch("https://swapi.co/api/people/1", {
    formatter: (response) => response.text()
});

Multiple requests

Multiple instances of useFetch in the same file/component is supported:

const result1 = useFetch("https://swapi.co/api/people/1");
const result2 = useFetch("https://swapi.co/api/people/2");if (result1.isLoading && result2.isLoading) {
  return <div>Loading...</div>;
}  return <div>
    <UserProfile {...result1.data} />
    <UserProfile {...result2.data} />
</div>

use-onclickoutside

This is a React Hook for listening for clicks outside of an element. It’s useful in combination with modals, pop-ups, alerts, or profile navigation.

Getting started

Yarn

yarn add use-onclickoutside

Usage

We create a ref and pass the ref to the useOnClickOutside Hook.

import React, { useRef } from 'react'
import useOnClickOutside from 'use-onclickoutside'export default function Modal({ close }) {
  const ref = useRef(null)
  useOnClickOutside(ref, close)  return <div ref={ref}>{'Modal content'}</div>
}

Notice the usage of useRef, which is a standard React Hook provided by the standard React package.

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component

Conclusion

Thanks for reading, I hope you learned something new. Happy coding!

react react-hooks react-js

What's new in Bootstrap 5 and when Bootstrap 5 release date?

How to Build Progressive Web Apps (PWA) using Angular 9

What is new features in Javascript ES2020 ECMAScript 2020

Deno Crash Course: Explore Deno and Create a full REST API with Deno

How to Build a Real-time Chat App with Deno and WebSockets

Convert HTML to Markdown Online

HTML entity encoder decoder Online

Random Password Generator Online

HTML Color Picker online | HEX Color Picker | RGB Color Picker

Hire React Js Developer from Expert React JS Development Company

Are you looking to [hire React JS developer](https://www.mobiwebtech.com/react-js-development-company/ "hire React JS developer") from a prestigious and reliable React JS development company? Visit at Mobiweb Technologies here we have a big team...

React Hooks Tutorial for Beginners: Getting Started With React Hooks

React hooks tutorial for beginners, learn React hooks step by step: Introduction, useState Hook, useState with previous state, useState with object, useState with array, useEffect Hook, useEffect after render, Conditionally run effects, Run effects only once, useEffect with cleanup, useEffect with incorrect dependency, Fetching data with useEffect, useContext Hook, useReducer Hook, useReducer, Multiple useReducers, useReducer with useContext, Fetching data with useReducer, useState vs useReducer, useCallback Hook, useMemo Hook, useRef Hook

React Hooks with Redux Hooks

How to integrate redux Hooks in a Project with React using hooks (not classes ) I made a tutorial from scratch on how to work with it.

Convert String To Number/Array In JavaScript with React Hooks/Vue.JS Examples

In this tutorial, we'll learn by example how to convert a string to the corresponding integer or float number or array of numbers using the built-in JavaScript methods with simple React and Vue.js examples.

State Management with React Hooks and RxJS

In this article, we’ll cover the basics of RxJS and how to integrate it with React applications using React Hooks for state management.