Here Are 6 Awesome React Hooks

Did you know there are thousands of useful React Hooks that you can start using today?

Indrek Lasn
Oct 31 · 6 min read
Photo by Oskar Yildiz on Unsplash

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.

Note: If React Hooks are a new concept to you, check out my previous post “Demystifying React Hooks.”

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.

@rehooks/component-size GitHub page

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.

ResizeObserver browser support

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

@rehooks/window-scroll-position

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.

@rehooks/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.

react-use-form-state

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 react@^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: 'mary@example.com',
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
react-fetch-hook

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.

use-onclickoutside

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!

Better Programming

Advice for programmers.

Indrek Lasn

Written by

Software Engineer. I try to be kind and friendly. Let’s change the world together for the better. Follow me on Twitter @ https://twitter.com/lasnindrek

Better Programming

Advice for programmers.