Skip to content

Instantly share code, notes, and snippets.

@cbejensen
Last active March 29, 2019 22:11
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cbejensen/dc0a6bf33c3d0e6dfcf8e7c404947389 to your computer and use it in GitHub Desktop.
Save cbejensen/dc0a6bf33c3d0e6dfcf8e7c404947389 to your computer and use it in GitHub Desktop.
Async Effect Hook
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>
}
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)
}
@cbejensen
Copy link
Author

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!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment