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.
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.
The useInput hook is used to simplify the handling of input events. Here is how you can install this custom hook.
Check out the useInput sandbox example here.
useKeyBindings is used to bind pairs of keyboard events and handlers.
Sandbox demo link.
useOnline is the status hook used to detect whether the user is online or offline. The return value will be boolean(True or false).
usePrevious hook enables you to access the previous value of a variable.
The use WindowSize hook is used to return the window size that includes inner height and width and outer height and width.
useAsync hook resolves async function or a function that returns a promise. Here is how we can use it.
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
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!