Skip to content

Instantly share code, notes, and snippets.

@bartdorsey
Last active September 15, 2021 20:33
Show Gist options
  • Save bartdorsey/0170ad43ce7c152a1a9a4538f412e343 to your computer and use it in GitHub Desktop.
Save bartdorsey/0170ad43ce7c152a1a9a4538f412e343 to your computer and use it in GitHub Desktop.
useAsyncEffect - Like useEffect but without an Async IIFE
import { useEffect } from 'react';
export default function useAsyncEffect(callback, dependencies) {
useEffect(() => {
(async() => {
return await callback();
})();
}, dependencies);
}
// How to use this.
// const App = () => {
// const [users, setUsers] = useState([]);
//
// useAsyncEffect(async () => {
// const response = await fetch('/api/users');
// const users = await response.json();
// setUsers(users);
// return () => {
// console.log("This is cleanup");
// }
// },[]);
//
// return (
// <Users users={users}/>
// );
//}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment