Orlan Quijada

React Hooks

Mini react hooks that can be copy-pasted.

Nov 21, 2022
wip

useClickOutside

import { RefObject, useCallback, useEffect } from 'react'

export function useClickOutside(
  elementRef: RefObject<HTMLElement>,
  callback: (event: MouseEvent) => void,
) {
  const handleClick = useCallback(
    (event: MouseEvent) => {
      if (
        elementRef.current &&
        !elementRef.current.contains(event.target as Node)
      )
        callback(event)
    },
    [callback, elementRef],
  )

  useEffect(() => {
    addEventListener('click', handleClick)
    return () => removeEventListener('click', handleClick)
  }, [handleClick])
} 

useIsomorphicLayoutEffect

import { useEffect, useLayoutEffect } from 'react'

export const useIsomorphicLayoutEffect =
  typeof window !== 'undefined' ? useLayoutEffect : useEffect