Skip to content

Instantly share code, notes, and snippets.

@AlpacaGoesCrazy
AlpacaGoesCrazy / useOutsideClick.js
Last active July 22, 2019 13:50
React hook and HOC for handling clicks outside your component
/* Hook for handling click outside your react component */
const useOutsideClick = (onOutsideClick) => {
const elementRef = useRef(null)
useEffect(() => {
const handleOutsideClick = (e) => {
if(typeof onOutsideClick === 'function' && !elementRef.current.contains(e.target)) {
onOutsideClick(e)
}
}
document.addEventListener('mousedown', handleOutsideClick, false)
@AlpacaGoesCrazy
AlpacaGoesCrazy / useSafeState.js
Last active December 7, 2020 17:49
Hook for react state which prevents updates on unmounted components
import { useEffect, useRef, useState } from 'react'
/*
If you attempt to set some state after asynchronous request it may happen that component you wish to set state on has been unmounted.
This will trigger "Warning: Can’t call setState (or forceUpdate) on an unmounted component." warning.
This hooks is `useState` hook which prevents setting state on an unmounted component
Usage:
const [myState, mySafeSetState] = useSafeState(initialValue)
*/
const useSafeState = (initialValue) => {