Skip to content

Instantly share code, notes, and snippets.

View mic-css's full-sized avatar

Michele Cassano mic-css

View GitHub Profile
@mic-css
mic-css / useIsMounted.ts
Last active April 14, 2020 11:33
Custom hook that keeps track of whether a component is mounted, useful for canceling asynchronous setStates
import { useRef, useEffect } from 'react'
export const useIsMounted = () => {
const isMounted = useRef(false)
useEffect(() => {
isMounted.current = true
return () => {
isMounted.current = false
@mic-css
mic-css / usePrevious.ts
Last active May 6, 2020 10:22
Custom hook that keeps track of the previous value of an object or primitive, useful for comparing props between renders
import { useEffect, useRef } from 'react'
export function usePrevious<T>(value: T) {
const ref = useRef<T>()
useEffect(() => {
ref.current = value
})
return ref.current
@mic-css
mic-css / asyncWrap.ts
Last active May 6, 2020 10:26
Custom wrapper function for destructuring asynchronous requests into loading, error and result states
export const asyncWrap = (promise: Promise<any>) =>
promise
.then(result => [false, null, result])
.catch(err => [false, err, null])
// Usage
const [isLoading = true, err, result] = asyncWrap(asynchronousTask())