{

Syntax & Soul

}

Featured Post

TypeScript React
8 min read

Understanding TypeScript Generics with React Hooks

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];
}
                    
Author Sarah Mitchell
Read Full Article →

Explore Topics

Recent Posts

JavaScript
5 min read

The Magic of JavaScript Closures

Diving deep into closures, one of the most powerful features of JavaScript that enables data encapsulation and module patterns.

May 18, 2023 Read →
CSS Animation
7 min read

Mastering CSS Grid for Complex Layouts

Learn how to create intricate, responsive layouts using CSS Grid without resorting to hacky solutions or extra markup.

May 12, 2023 Read →
Node.js Performance
10 min read

Optimizing Node.js Applications for Production

Essential strategies to improve the performance, security, and reliability of your Node.js applications before deployment.

May 5, 2023 Read →
React TypeScript
6 min read

Building Type-Safe React Components

A comprehensive guide to leveraging TypeScript with React to create robust, error-resistant component libraries.

Apr 28, 2023 Read →
GraphQL API
8 min read

GraphQL vs REST: Making the Right Choice

An objective comparison of GraphQL and REST API architectures with practical examples for when to use each approach.

Apr 21, 2023 Read →
DevOps Docker
12 min read

Containerizing Your Development Environment

A step-by-step guide to setting up a consistent, reproducible development environment using Docker containers.

Apr 14, 2023 Read →

Code Snippets

Useful Array Methods


// 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}`);
                    

React Custom Hook


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;
}