Skip to content

Instantly share code, notes, and snippets.

@ntatko
Last active September 25, 2025 19:42
Show Gist options
  • Select an option

  • Save ntatko/4bae7b3efee0f5385e5500c73d168b63 to your computer and use it in GitHub Desktop.

Select an option

Save ntatko/4bae7b3efee0f5385e5500c73d168b63 to your computer and use it in GitHub Desktop.
// Reusable fetching hook
const useRequest = (requestFunc) => {
const [data, setData] = useState({})
const [loading, setLoading] = useState(false)
const [error, setError] = useState(null)
const fetch = async () => {
setLoading(true)
try {
const data = await requestFunc()
setData(data)
} catch (e) {
setError(e)
} finally {
setLoading(false)
}
})
useEffect(() => {
fetch()
}, [fetch, requestFunc])
return {data, loading, error, refetch: fetch}
}
// Your react component
const Component = ({ id }) => {
const { data, loading, error, refetch } = useRequest(
() => fetch(`/data/${id}`)
)
const [state, setState] = useState(null)
useEffect(() => {
refetch()
}, [state])
if (error) return <ErrorScreen />
if (loading) return <Spinner />
return <>{data.property}</>
}
@starjumper30
Copy link

Why do you have the code wrapped in an IIFE inside the function passed to useEffect?

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