Hey guys 😃
Since the introduction of Hooks in React, you may have used the same repetitive and redundant state logic inside several components. But with the Hooks, we can do it in a much simpler and cleaner way, thanks to Custom React Hooks.
The different hooks shared in this article are simple and avoid code repetition.
You will find below several custom Hooks without the need to download packages on npm or yarn.
This will allow you to modify them as you wish.
use and that may call other Hooks. For example,
useTheme below is our first custom Hook.
Your version of React must be at least 16.8.
Let's start with a simple custom React Hook to help you implement a "light/dark mode" component for your application. The user setting persists to localStorage and the default value is the
prefers-color-schema value if this one is supported.
This hook makes it easy to dynamically change the appearance of your app using CSS variables.
And for the CSS, just use the
data-theme attribute and the power of CSS variables to create our themes.
The hook will allow you to easily manage the viewport of the user's device. You will be able to retrieve the width of the screen but also to know if the screen size corresponds to a mobile, a tablet or a desktop.
Your components may be different depending on the width of the screen, but here is an idea of how to use this custom React hook.
Do you want to copy a text or an image and read the content from the clipboard ? Well here is a custom Hook using the new Clipboard API.
In this hook, two important things:
- Reading and writing to the clipboard are asynchronous.
- 2 permissions are required to use the
writemethods of the clipboard.
A very popular feature on websites is the ability to copy an element to your clipboard by a single click to a button. Let's copy a dynamic text value!
Have you ever wondered if the tabs/windows are using precious CPU time? Thanks to the Page Visibility API, we can detect when users are not viewing or interacting with our website, saving them valuable resources.
The visibility API allows a developer to know when a page has lost the focus. The API sends a
visibilitychange event of the visibility of the page.
So it can be used for things like:
- Pause a video when the page has lost user focus.
- Change the page title.
- Stop an HTML5 canvas animation when a user is not on the page.
- Display a notification to the user only when the page is active.
- Stop the movement of a carousel.
Let's change the title of the page if the user is not viewing the page.
With this hook, you'll be able to control the scroll
y of the page and to go back to the top/bottom with a smooth scroll. This can allow you to create an infinity scroll (
Let's show a newsletter popup if the user has scrolled to the bottom of the page.
Feel free to use these modern hooks ! The links to the gists associated with this article can be found below: