Skip to content

Instantly share code, notes, and snippets.

@mg901
Created June 9, 2026 13:28
Show Gist options
  • Select an option

  • Save mg901/77ce83135662c41be00fc8d26975261e to your computer and use it in GitHub Desktop.

Select an option

Save mg901/77ce83135662c41be00fc8d26975261e to your computer and use it in GitHub Desktop.
import { useRef, useState, useEffect } from "react";
/**
* @template T
* @param {() => Promise<T>} fn
* @param {import("react").DependencyList} deps
*/
export default function useQuery(fn, deps = []) {
const latestFn = useRef(fn);
const [state, setState] = useState({ status: "loading" });
useEffect(() => {
latestFn.current = fn;
}, [fn]);
useEffect(() => {
let canceled = false;
setState({ status: "loading" });
latestFn
.current()
.then((data) => {
if (canceled) return;
setState({
status: "success",
data,
});
})
.catch((error) => {
if (canceled) return;
setState({
status: "error",
error,
});
});
return () => {
canceled = true;
};
}, deps);
return state;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment