DEV Community

DhiWise
DhiWise

Posted on • Edited on

Custom Hooks to Lightweight Your React Project

React Custom Hooks

Hooks are the JavaScript functions that let you add additional functionality to the React apps without writing a class. React provides built-in hooks such as useState, useEffect, useContext and also facilitates you to create custom hooks.

React hooks were introduced in React Version 16.8 and above and one of its main advantages is the reusability of stateful logic. Before the introduction of hooks, states can be maintained only in the class components but with the addition of hooks, states can now be maintained in the functional components without changing the component hierarchy.

Let’s take a look at some useful custom hooks in React and understand how to use them in your project.

useTheme

The useTheme hook helps you to dynamically change the appearance of your application using CSS variables. This can be done by simply passing an object containing the key/value pair of the CSS variables you would like to modify.

The hook helps you to implement the light/dark components in your app.

useTheme custom hook

useInput

The useInput hook is used to simplify the handling of input events. Here is how you can install this custom hook.

useInput hooks

Check out the useInput sandbox example here.

useKeyBindings

useKeyBindings is used to bind pairs of keyboard events and handlers.

Sandbox demo link.

useOnline

useOnline is the status hook used to detect whether the user is online or offline. The return value will be boolean(True or false).

useOnline hook

Sandbox demo.

usePrevious

usePrevious hook enables you to access the previous value of a variable.

usePrevious hook

Sandbox demo.

useWindowSize

The use WindowSize hook is used to return the window size that includes inner height and width and outer height and width.

Sandbox demo.

useAsync

useAsync hook resolves async function or a function that returns a promise. Here is how we can use it.

useAsync hook

usePageVisibility

With the page Visibility hook, you can detect whether users are interacting with our website or not. It sends a visibility change event when the user lost focus on the page.

So the hook can be used to,

  • Pause a video on page has lost user focus

  • Page title changed

  • To stop HTML canvas animation when the user is not on page

  • Send notification or messages to the user on the page is active

Feel free to use these modern react hooks you can find more custom hooks in the react-use package and Github rooks.

So, this is all about React custom hooks. Hope you enjoy this article.

Want to build a lightweight, scalable, and quality application faster? Try DhiWise- A 100% developer-centric platform to build modern applications with the technology you love.

Explore more about DhiWise and the technologies it support.

Sign up Now!

Top comments (0)