DEV Community

Juan Cruz Martinez
Juan Cruz Martinez

Posted on • Originally published at livecodestream.dev on

7 Awesome React Hooks

Before the release of React Hooks, its functional components were a bit limited in usage. I mean, when it comes to working with State, 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 ready and follow along with me on this interesting journey.


useFiler Hook

There is a very cool collection of hooks by Christopher Patty which is known as “crooks".

I personally like its 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

Enter fullscreen mode Exit fullscreen mode

Now, import useFiler hook from crooks.

import { useFiler } from 'crooks'

Enter fullscreen mode Exit fullscreen mode

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

const App = () => {
  const [files, {add, remove, update, clear}] = useFiler("localStorageItem")

  return (
    <div>My Project</div>
  )
}

Enter fullscreen mode Exit fullscreen mode

As you can see from the above code that we now have access to 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 a JSON-serializable data.

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

Enter fullscreen mode Exit fullscreen mode

A point to be noted is that 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

The update() 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.")

Enter fullscreen mode Exit fullscreen mode

Remove File

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

remove("abc1234")

Enter fullscreen mode Exit fullscreen mode

Clear All Files

Call the clear() function to remove all files.

clear()

Enter fullscreen mode Exit fullscreen mode

useFetch Hook

Steven Persia (a MERN Stack developer), has compiled a great list of React Hooks called “Captain hook” that is very helpful in everyday tasks.

The next few examples of Hooks will be from his collection, including this one.

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

Enter fullscreen mode Exit fullscreen mode

Make a request.

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

Enter fullscreen mode Exit fullscreen mode

useHover Hook

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

Enter fullscreen mode Exit fullscreen mode

Initialize useHover hook.

const [hoverMe, isHovered] = useHover();

Enter fullscreen mode Exit fullscreen mode

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>

Enter fullscreen mode Exit fullscreen mode

useSlug Hook

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

Enter fullscreen mode Exit fullscreen mode

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

Enter fullscreen mode Exit fullscreen mode

useDrag & 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 get an idea about what they do. But still, I have to mention that they help us with the Drag & Drop functionality of HTML5.

Install

npm install ahooks --save

Enter fullscreen mode Exit fullscreen mode

Import the Hooks

import { useDrag, useDrop } from 'ahooks';

Enter fullscreen mode Exit fullscreen mode

Usage

First of all, initialize the useDrag and useDrop Hooks.

useDrag return props that are passed to a DOM element. Whereas, useDrop returns props that are passed to a drop area. It also informs us 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
const getDragProps = useDrag();

const [props, { isHovering }] = useDrop({
  onText: (text, e) => {
    alert(`'text: ${text}' dropped`);
  },
  onFiles: (files, e) => {
    alert(`${files.length} file dropped`);
  },
  onUri: (uri, e) => {
    alert(`uri: ${uri} dropped`);
  },
  onDom: (content: string, e) => {
    alert(`custom: ${content} dropped`);
  }
});

Enter fullscreen mode Exit fullscreen mode

An HTML5 element that you can drag using a mouse.

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

Enter fullscreen mode Exit fullscreen mode

An HTML5 element where you can drop something.

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

Enter fullscreen mode Exit fullscreen mode

useDarkMode Hook

Craig Walker originally developed “React Recipes". A popular collection of customized React Hooks.

It offers useDarkMode Hook to toggle between light and dark mode of the website theme. After switching the mode, it stores the current value in a localStorage. It 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

Enter fullscreen mode Exit fullscreen mode

Import

import { useDarkMode } from "react-recipes";

Enter fullscreen mode Exit fullscreen mode

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.
function App() {
  const [darkMode, setDarkMode] = useDarkMode();

  return (
    <div className="header">
      <Toggle darkMode={darkMode} setDarkMode={setDarkMode} />
    </div>
  );
}

Enter fullscreen mode Exit fullscreen 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 code in our React projects using Hooks. In fact, the main plus point of React Hooks is that it enables us to write better and reusable code.

Thanks for reading!


If you like the story, please don't forget to subscribe to our free newsletter so we can stay connected: https://livecodestream.dev/subscribe

Top comments (1)

Collapse
 
stevenpersia profile image
Steven Persia

Thank you :)