Just built this custom React hook for managing complex API state with caching and optimistic updates! Perfect for handling real-time data. 🚀
const useApiWithCache = (url, options = {}) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
const cacheKey = `${url}-${JSON.stringify(options)}`;
useEffect(() => {
// Check cache first
const cached = sessionStorage.getItem(cacheKey);
if (cached && !options.refresh) {
setData(JSON.parse(cached));
setLoading(false);
return;
}
// Fetch with optimistic updates
fetch(url, options)
.then(res => res.json())
.then(result => {
setData(result);
sessionStorage.setItem(cacheKey, JSON.stringify(result));
})
.catch(setError)
.finally(() => setLoading(false));
}, [url, cacheKey]);
return { data, loading, error, refetch: () => fetch(url, {...options, refresh: true}) };
};