Last active
March 29, 2019 22:11
-
-
Save cbejensen/dc0a6bf33c3d0e6dfcf8e7c404947389 to your computer and use it in GitHub Desktop.
Async Effect Hook
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 from 'react' | |
import useEffectAsync from './useEffectAsync' | |
export default function Brownies() { | |
const [brownies, setBrownies] = useState('Loading') | |
useEffectAsync( | |
async didUnmount => { | |
const res = await fetch(`https://api.brownies.com`) | |
if (!didUnmount) setBrownies(res) | |
}, | |
[] | |
) | |
return <div>{brownies}</div> | |
} |
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 { useEffect } from 'react' | |
export default function useEffectAsync(asyncFunc, triggers) { | |
// avoid side effects from async func after component unmounts | |
useEffect(() => { | |
let didUnmount = false | |
asyncFunc(didUnmount) | |
return () => (didUnmount = true) | |
}, triggers) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This simple, custom hook allows you to perform an asynchronous function and carry out side effects without worrying about race conditions, since you can perform an easy check to see if the component has unmounted.
This is the simplest and most re-usable way of doing this I could come up with. If you have a better way, please comment!