Skip to content

Instantly share code, notes, and snippets.

@dnshko
Created August 2, 2020 13:25
Show Gist options
  • Save dnshko/ce0cb4bec9b3ab6975c07af889ead5fc to your computer and use it in GitHub Desktop.
Save dnshko/ce0cb4bec9b3ab6975c07af889ead5fc to your computer and use it in GitHub Desktop.
useRef
const useFetch = (url) => {
const cache = useRef({});
const [status, setStatus] = useState('idle');
const [data, setData] = useState([]);
useEffect(() => {
if (!url) return;
const fetchData = async () => {
setStatus('fetching');
if (cache.current[url]) {
const data = cache.current[url];
setData(data);
setStatus('fetched');
} else {
const response = await fetch(url);
const data = await response.json();
cache.current[url] = data; // set response in cache;
setData(data);
setStatus('fetched');
}
};
fetchData();
}, [url]);
return { status, data };
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment