franlol
franlol

Reputation: 51

When to use hooks? is worth it that example?

I have write a hook to check if browser is IE, so that I can reutilize the logic instead of write it in each component..


const useIsIE = () => {
    const [isIE, setIsIE] = useState(false);

    useEffect(() => {
        const ua = navigator.userAgent;
        const isIe = ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;

        setIsIE(isIe);
    }, []);

    return isIE;
}

export default useIsIE;

Is it worth it to use that hook? Im not sure if is good idea because that way, Im storing a state and a effect for each hook call (bad performane?) when I can simply use a function like that:

export default () => ua.indexOf("MSIE ") > -1 || ua.indexOf("Trident/") > -1;

What do you think? is worth it use that hook or not? If not, when should I use hooks and when not?

ty

Upvotes: 1

Views: 290

Answers (2)

joseluismurillorios
joseluismurillorios

Reputation: 1014

I would recommend to set your browser checks in constants and not functions, your browser will never change.

...
export const isChrome = /Chrome/.test(userAgent) && /Google Inc/.test(navigator.vendor);
export const isIOSChrome = /CriOS/.test(userAgent);
export const isMac = (navigator.platform.toUpperCase().indexOf('MAC') >= 0);
export const isIOS = /iphone|ipad|ipod/.test(userAgent.toLowerCase());
...

This is a simple hook that checks if a element has been scrolled a certain amount of pixels

const useTop = (scrollable) => {
  const [show, set] = useState(false);

  useEffect(() => {
    const scroll = () => {
      const { scrollTop } = scrollable;
      set(scrollTop >= 50);
    };

    const throttledScroll = throttle(scroll, 200);

    scrollable.addEventListener('scroll', throttledScroll, false);

    return () => {
      scrollable.removeEventListener('scroll', throttledScroll, false);
    };
  }, [show]);

  return show;
};

Then you can use it in a 'To Top' button to make it visible

...
import { tween } from 'shifty';
import useTop from '../../hooks/useTop';

// scrollRef is your scrollable container ref (getElementById)
const Top = ({ scrollRef }) => {
  const t = scrollRef ? useTop(scrollRef) : false;
  return (
    <div
      className={`to-top ${t ? 'show' : ''}`}
      onClick={() => {
        const { scrollTop } = scrollRef;
        tween({
          from: { x: scrollTop },
          to: { x: 0 },
          duration: 800,
          easing: 'easeInOutQuart',
          step: (state) => {
            scrollRef.scrollTop = state.x;
          },
        });
      }}
      role="button"
    >
      <span><ChevronUp size={18} /></span>
    </div>
  );
};

Upvotes: 0

dance2die
dance2die

Reputation: 36895

No. Not worth using the hook.

You'd need to use a hook when you need to tab into React's underlying state or lifecycle mechanisms.

Your browser will probably NEVER change during a session so just creating a simple utility function/module would suffice.

Upvotes: 1

Related Questions