Skip to content

Instantly share code, notes, and snippets.

@amsterdamharu
Last active March 17, 2021 19:15
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save amsterdamharu/5c44d3c3b32c11571e0cdca191e1dd36 to your computer and use it in GitHub Desktop.
const useIsMounted = () => {
const isMounted = useRef(false);
useEffect(() => {
isMounted.current = true;
return () => (isMounted.current = false);
}, []);
return isMounted;
};
const useSetIfIsMounted = setter => {
const isMounted = useIsMounted();
return value =>
isMounted.current ? setter(value) : null;
};
const setDataIfMounted = useSetIfIsMounted(setData);
useEffect(() => {
const fetchData = async () => {
const result = await fetch(SlowestResponse);
const jsonresponse = await result.json();
setDataIfMounted([jsonresponse]);
};
fetchData();
}, []);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment