Won't this rerun if shouldSetData changes while fetching?
- User
Won't this rerun if shouldSetData changes while fetching?
Assistant
You're right. The current implementation would restart the fetch if
shouldSetDatachanges during fetching. Here's a corrected version using a ref to check the current value without triggering re-fetches:import { useState, useEffect, useRef } from 'react'; const useAsyncData = (fetchData, shouldSetData) => { const [data, setData] = useState(null); const [loading, setLoading] = useState(false); const shouldSetDataRef = useRef(shouldSetData); // Update ref when shouldSetData changes useEffect(() => { shouldSetDataRef.current = shouldSetData; }, [shouldSetData]); useEffect(() => { const loadData = async () => { setLoading(true); try { const result = await fetchData(); if (shouldSetDataRef.current) setData(result); } finally { setLoading(false); } }; loadData(); }, [fetchData]); // Only depend on fetchData return { data, loading }; }; export default useAsyncData;
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.