Created
June 15, 2020 14:56
-
-
Save memon07/bc9b07054777aaa3c80d84a007036a51 to your computer and use it in GitHub Desktop.
Custom hook to prevent memory leakage
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { | |
Dispatch, | |
SetStateAction, | |
useState, | |
useRef, | |
useEffect, | |
} from 'react'; | |
export default function useMountedState<S>( | |
initialState: S | (() => S), | |
): [S, Dispatch<SetStateAction<S>>] { | |
const [state, setState] = useState(initialState); | |
const ref = useRef(false); | |
const updateState = (value: SetStateAction<S>) => { | |
ref.current && setState(value); | |
}; | |
useEffect(() => { | |
ref.current = true; | |
return () => { | |
ref.current = false; | |
}; | |
}, []); | |
return [state, updateState]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment