Unstuck in Time: Top 10 Async Techniques in React/JavaScript!
Hey there, budding web dev! Ever felt like you’re stuck in a non-ending loop, waiting for data to load? You’re not in a Groundhog Day scenario. It’s just async in JavaScript! 😉 Let’s untangle the mystery and speed things up!
1. Async/Await: The Knight in Shining Armor
ES8 introduced this beauty, making asynchronous code read like synchronous.
async function fetchData() {
try {
let response = await fetch('api/data');
let data = await response.json();
console.log(data);
} catch (error) {
console.error("Error fetching data:", error);
}
}
fetchData();
2. Promises: Seal the Deal
Promises handle future values. They can be in 3 states: pending
, resolved
, or rejected
.
let promise = new Promise((resolve, reject) => {
setTimeout(() => {
resolve("Data received!");
// or
// reject("Error fetching data");
}, 1000);
});
promise.then(data => console.log(data)).catch(error => console.error(error));3. Fetch API: Net the Web
3. Fetch API: Modern Data Fetching
It returns a promise. Always remember error handling.
fetch('api/data')
.then(response => {
if (!response.ok) {
throw new Error("Network response was not ok");
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error("Fetch error:", error));
4. Callbacks: Ol’ Reliable
Though slightly out of fashion due to “callback hell”, they’re foundational.
function fetchData(callback) {
// Mock data fetch
setTimeout(() => {
const data = "Here's your data!";
callback(null, data);
}, 1000);
}
fetchData((error, data) => {
if (error) console.error(error);
else console.log(data);
});
5. Defer Attribute: Delay the JS
Speed up initial page loads by deferring non-essential scripts.Deferring scripts ensures they’re executed in order after the HTML is parsed.
<script src="script.js" defer></script>
6. Throttling and Debouncing: Avoid the Overwhelm
Great for performance, especially with events like scrolling or resizing. Throttle: limited calls. Debounce: delay till last call.
// Using lodash
// Throttle: Call at most once every 200ms
window.addEventListener('resize', _.throttle(() => console.log('Resizing!'), 200));
// Debounce: Call once 300ms after the last invocation
window.addEventListener('scroll', _.debounce(() => console.log('Scrolling!'), 300));
7. Web Workers: Employ Parallelism
Run scripts in the background, especially heavy computations
let worker = new Worker("worker.js");
worker.postMessage('Start computation!');
worker.onmessage = function(event) {
console.log('Received data from worker:', event.data);
};
8. Virtual Scrolling: Display On Demand
Load only what’s visible. Ideal for long lists.
// Using React-Virtualized
<AutoSizer>{({ height, width }) => (
<List
height={height}
rowCount={1000}
rowHeight={40}
rowRenderer={({ index, style }) => (
<div style={style}>Row {index}</div>
)}
width={width}
/>
)}</AutoSizer>
9. Intersection Observer: Lazy Loading
Only load content when it’s in view.
let observer = new IntersectionObserver(entries => {
entries.forEach(entry => {
if (entry.isIntersecting) {
console.log("Element is in view!");
}
});
});
observer.observe(document.querySelector('.targetElement'));
10. Suspense & Lazy (React): Smooth Component Loading
Load React components lazily.
const LazyComponent = React.lazy(() => import('./LazyComponent'));
function App() {
return (
<Suspense fallback={<div>Loading...</div>}>
<LazyComponent />
</Suspense>
);
}
Async in JavaScript is like life — unpredictable but manageable. Dive into these techniques and keep your codebase as zippy as a caffeinated squirrel! 🐿️ Happy coding!
Dive deeper into the developer’s realm on my Medium: shubhamgautamlog.medium.com. 📖
Want to chat or geek out about the latest in web dev? 🚀
Don’t forget to share the love and the article! Sharing is caring, after all. 😉👍