The Magic of JavaScript Closures
Diving deep into closures, one of the most powerful features of JavaScript that enables data encapsulation and module patterns.
Leverage the power of TypeScript generics to create type-safe custom React hooks that improve code maintainability and prevent runtime errors.
function useLocalStorage<T>(key: string, initialValue: T): [T, (value: T) => void] {
// Get from local storage then parse stored json or return initialValue
const [storedValue, setStoredValue] = useState<T>(() => {
if (typeof window === "undefined") return initialValue;
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
console.error(error);
return initialValue;
}
});
// Return a wrapped version of useState's setter function
const setValue = (value: T) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
}
Diving deep into closures, one of the most powerful features of JavaScript that enables data encapsulation and module patterns.
Learn how to create intricate, responsive layouts using CSS Grid without resorting to hacky solutions or extra markup.
Essential strategies to improve the performance, security, and reliability of your Node.js applications before deployment.
A comprehensive guide to leveraging TypeScript with React to create robust, error-resistant component libraries.
An objective comparison of GraphQL and REST API architectures with practical examples for when to use each approach.
A step-by-step guide to setting up a consistent, reproducible development environment using Docker containers.
// Filter, map, and reduce combined in one example
const products = [
{ id: 1, name: 'Laptop', price: 999, inStock: true },
{ id: 2, name: 'Phone', price: 699, inStock: true },
{ id: 3, name: 'Tablet', price: 399, inStock: false },
{ id: 4, name: 'Mouse', price: 29, inStock: true }
];
// Get the total cost of all available products
const totalInStockValue = products
.filter(product => product.inStock)
.map(product => product.price)
.reduce((total, price) => total + price, 0);
console.log(`Total inventory value: $${totalInStockValue}`);
import { useState, useEffect } from 'react';
// Custom hook for window dimensions
function useWindowSize() {
const [windowSize, setWindowSize] = useState({
width: undefined,
height: undefined,
});
useEffect(() => {
// Handler to call on window resize
function handleResize() {
setWindowSize({
width: window.innerWidth,
height: window.innerHeight,
});
}
// Add event listener
window.addEventListener('resize', handleResize);
// Call handler right away so state gets updated
handleResize();
// Remove event listener on cleanup
return () => window.removeEventListener('resize', handleResize);
}, []); // Empty array ensures effect runs only on mount and unmount
return windowSize;
}