DEV Community

Amandeep Singh
Amandeep Singh

Posted on • Edited on

Some Custom React Hooks I've used so far.

Hi there,
As we all know, ReactJS is currently the most popular front-end framework. Some years back, a powerful feature was introduced by React devs - React Hooks, where they moved from class-based programming approach to function-based, which turned out to be a game changer!

In addition to the in-built hooks from React's, like useState, useEffect, useContext etc., devs can write their own hooks - termed as Custom Hooks.

In this post, I'm gonna mention my favorite custom hooks, which I found useful for my projects.

useLocalStorage:

The usage is similar to useState, but instead of storing the value in virtual state, we store it in browser's local storage and the value is persisted on page refresh.

Example:
If your site has dark theme mode, you can use the hook to persist theme's switch. So, whenever user returns to your site, it'll apply the theme automatically.

Source code & usage


useMediaQuery

If you're aware of media queries from CSS, you'll get the usage info. from the name itself. Basically, you can use this when you want to conditionally render something according to device-screen's width.

Example:
Without using CSS, you can un-render mobile menu component, whenever screen size exceeds 768px.

Source code & usage


useClickOutside

With this hook, you can detect click events outside of a particular element.

Example:
If you have a modal/dialog component, you want it to close whenever user clicks outside of the main element.

Source code & usage


useScrollDown

This hook will return true, if the scroll hits the specified value.

Example:
If you have a floating button for scroll up, but you only want it to show when your page is scrolled down a bit from initial position.

Source Code:

import { useState, useEffect } from 'react';

const useScrollDown = (height) => {
  const [boolean, setBoolean] = useState(false);

  const handler = () => {
    if (window.pageYOffset >= height) {
      setBoolean(true);
    } else {
      setBoolean(false);
    }
  };

  useEffect(() => {
    window.addEventListener('scroll', handler);
    return () => window.removeEventListener('scroll', handler);
  }, []);

  return boolean;
};

export default useScrollDown;
Enter fullscreen mode Exit fullscreen mode

Usage:

const isScrollDown = useScrolldown(90);

return (
  <div>
    {isScrollDown ? "It's down!" : "Initial position."}
  </div>
)
Enter fullscreen mode Exit fullscreen mode

Top comments (1)

Collapse
 
scriptkavi profile image
ScriptKavi

Why create one when you can get all awesome hooks in a single library?

Try scriptkavi/hooks. Copy paste style and easy to integrate with its own CLI