10LOC

#state-management

Reactintermediate

A tiny useLocalStorage hook

import { useState, useEffect } from "react";

export const useLocalStorage = <T>(key: string, initialValue: T) => {
  const [value, setValue] = useState<T>(() => {
    const stored = localStorage.getItem(key);

Sync a single piece of state to localStorage with a small, focused hook.

Reactadvanced

useReducer with a discriminated-union action type

type State =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: string[] }
  | { status: "error"; error: string };

Model a fetch state machine as a discriminated union so an exhaustiveness check fails to compile the moment a reducer case is missing.