7 Awesome React Hooks

React Hooks you can use every day to boost your productivity

Juan Cruz Martinez
Jul 8 · 5 min read
Image for post
Image for post

Before the release of React Hooks, the framework’s functional components were a bit limited in usage. When it came to working with state, the context API, and some lifecycle methods, there was nothing we could do.

But starting from React 16.8, we have a lot more flexibility to reuse an existing piece of code.

Today, you will learn about the usage of different React hooks to solve everyday problems. So, let’s get started on this interesting journey.


useFiler Hook

There is a very cool collection of hooks by Christopher Patty that are known as crooks.

I personally like the useFiler hook because it enables us to create a virtual file system right inside a web browser. Basically, it makes use of the browser’s local storage to manage the files and their contents.

To get started, install the crooks package in your application:

npm install crooks --save

Now, import the useFiler hook from crooks:

import { useFiler } from 'crooks'

At this point, we are ready to initialize the hook and manage a virtual file system. Here’s a quick example code snippet:

As you can see from the code above, we now have access to the add(), remove(), update(), and clear() methods. Let’s have a look at how to use them.

Add file

The add() function accepts one required parameter. Here, we need to pass JSON-serializable data:

add("Save this JSON-serializable data in the file.")

Note: This function will automatically generate an ID for every new file, but you can still set a custom ID by passing an integer or string as the second parameter.

Update file

Theupdate() method accepts two arguments. The first one is the ID of the file, whereas the second argument is used to pass the new data:

update("abc1234", "New content of file.")

Remove file

Pass the ID of the file in the remove() function to delete it:

remove("abc1234")

Clear all files

Call the clear() function to remove all files:

clear()

useFetch Hook

Steven Persia (a MERN Stack developer) has compiled a great list of React hooks called Captain hook. They are very helpful in everyday tasks.

The next few examples of hooks will be from his collection.

useFetch can be used to get data from an API. After the request is completed, it will return the response and errors (if any).

Import it in your project:

import useFetch from "hooks/useFetch";

Make a request:

const { response, errors } = useFetch("https://api.github.com/users/torvalds/repos");

useHover Hook

The useHover hook belongs to the Captain hook collection.

Basically, it tracks the mouse cursor on the screen to detect whether it is placed on a specific element or not. If so, it will trigger the hovered event.

Import the hook:

import useHover from "hooks/useHover";

Initialize useHover hook:

const [hoverMe, isHovered] = useHover();

Here, hoverMe refers to the specific HTML element, whereas isHovered contains a boolean value that can be checked in a conditional statement.

For example, we can use something like this:

<div ref={hoverMe}>{isHovered ? "Hovered!" : "Hover me!"}</div>

useSlug Hook

The slug is an important part of every web project. In fact, it can also boost the SEO of a website.

That’s why Steven has added useSlug in his Captain hook collection. We can use it to quickly turn any string into an SEO-friendly slug. It’s smart enough to replace any diacritical marks (accents) with its standard counterpart.

For example, it will convert é or è into e.

As usual, we first need to import the hook:

import useSlug from "hooks/useSlug";

Usage

While initializing the hook, pass any string (e.g. an article title) as the first parameter. As a result, it will return a well-formed slug that can be used in a project right away:

useSlug("React Hooks! résoudre les problèmes quotidiens");// react-hooks-resoudre-les-problemes-quotidiens

useDrag and useDrop Hooks

There is an open-source React Hooks library called ahooks. It is actively being developed by the eCommerce giant Alibaba together with some volunteer contributors.

At the time of writing this article, it has around 46 hooks. Each of them is focused on solving a specific problem.

In this section, I’ll introduce you to a pair of hooks: useDrag and useDrop. By now, you might already have an idea of what they do. Still, I have to mention that they help us with the drag-and-drop functionality of HTML5.

Install:

npm install ahooks --save

Import the hooks:

import { useDrag, useDrop } from 'ahooks';

Usage

First of all, initialize the useDrag and useDrop hooks.

useDrag returns props that are passed to a DOM element. useDrop returns props that are passed to a drop area. It also informs us of whether the dragging element is on top of the drop area or not using a boolean property (isHovering).

Finally, useDrop has four callback functions that are executed based on the type of item dropped:

  • onText
  • onFiles
  • onUri
  • onDom

An HTML5 element that you can drag using a mouse:

<div {...getDragProps(id)}>Draggable Element</div>

An HTML5 element where you can drop something:

<div {...props}>
{isHovering ? 'Release Item Here' : 'Drop Anything Here'}
</div>

useDarkMode Hook

Craig Walker originally developed React Recipes, a popular collection of customized React hooks.

It offers the useDarkMode hook to toggle between the light and dark mode of the website theme. After switching the mode, it stores the current value in a localStorage. This means that the user’s preferred mode will be applied right away on all browser tabs where our website is opened.

Install the library:

npm install react-recipes --save

Import:

import { useDarkMode } from "react-recipes";

Quick example

Basically, useDarkMode() returns two things.

  • darkMode: A boolean value that is true when the dark mode is active.
  • setDarkMode: It toggles between light and dark mode.

Conclusion

Today, you have learned the use of React Hooks in everyday life. We just saw a few example use cases, but there are tons of open-source hooks available that you can include in your projects.

Now, I hope you are comfortable using someone else’s code in your React projects using hooks. In fact, the main benefit of React Hooks is that it enables us to write better and reusable code.

Thanks for reading!

Better Programming

Advice for programmers.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch

Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore

Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store