Here’s a plain JavaScript version of the same logic, mimicking the behavior of the React hook but without any framework dependencies:
Plain JavaScript Implementation
function asyncDataLoader(fetchData, shouldSetData) {
let data = null;
let loading = false;
let shouldSetDataRef = shouldSetData;
let isMounted = true;
const setLoading = (value) => {
if (!isMounted) return;
loading = value;
console.log("Loading:", loading); // For debugging
};
const setData = (value) => {
if (!isMounted) return;
data = value;
console.log("Data updated:", data); // For debugging
};
const loadData = async () => {
setLoading(true);
try {
const result = await fetchData();
if (shouldSetDataRef) setData(result);
} finally {
setLoading(false);
}
};
// Simulate React's "effect" by running immediately
loadData();
// Cleanup function (equivalent to useEffect's cleanup)
const cleanup = () => {
isMounted = false;
};
// Simulate updating `shouldSetDataRef` externally
const updateShouldSetData = (newValue) => {
shouldSetDataRef = newValue;
};
return {
getData: () => data,
isLoading: () => loading,
cleanup,
updateShouldSetData, // Allows external updates to `shouldSetData`
};
}
Usage Example
// Example fetch function
const fetchMockData = () =>
new Promise((resolve) =>
setTimeout(() => resolve({ id: 1, name: "Test" }), 1000)
);
// Initialize loader
const loader = asyncDataLoader(fetchMockData, true);
// Later, if `shouldSetData` changes (e.g., due to user action)
setTimeout(() => {
loader.updateShouldSetData(false); // Prevents future data updates
}, 500);
// Cleanup when no longer needed (e.g., component unmounts)
setTimeout(() => {
loader.cleanup();
}, 2000);
Key Differences from React Version
- No React State Management → Uses plain variables (
data, loading) and getter functions (getData(), isLoading()).
- Manual Cleanup → Explicit
cleanup() instead of useEffect's return function.
- No Automatic Dependency Tracking →
shouldSetDataRef must be updated manually via updateShouldSetData().
- No Re-renders → Changes to
data or loading don’t trigger UI updates (you’d need to poll or use events in a real app).
When to Use This?
- In vanilla JS projects.
- For testing the core logic without React.
- As a lightweight alternative if you don’t need reactivity.
Would you like a version that uses event listeners for reactivity?