10LOC

React

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.

Reactintermediate

Use React's use hook for promises and context

import { use, Suspense, createContext } from "react";

const ThemeContext = createContext("light");
const greetingCache = new Map<string, Promise<string>>();

Read promises and context directly during render with React's built-in use hook.

Reactadvanced

A stable latest-callback ref to kill effect dependency churn

import { useRef, useEffect, useCallback } from "react";

export const useLatestCallback = <Args extends unknown[], R>(callback: (...args: Args) => R) => {
  const callbackRef = useRef(callback);

Wrap a fast-changing callback in a ref so effects can call the latest version without listing it as a dependency and re-firing every render.

Reactintermediate

A form calling a Server Action directly, no client fetch

const subscribers = new Set<string>();

async function subscribeToNewsletter(formData: FormData) {
  "use server";

Wire a form straight to a Server Action with the action prop, skipping the client fetch, JSON body, and API route entirely.

Reactadvanced

useOptimistic for instant UI feedback before the server confirms

import { useOptimistic, useTransition } from "react";

type Post = { id: string; likedByMe: boolean; likeCount: number };

export const LikeButton = ({ post, toggleLike }: { post: Post; toggleLike: (id: string) => Promise<void> }) => {

Show the result of an action immediately and let React reconcile it with the real state once the server responds, success or failure.

Reactadvanced

Compound components with context instead of Children.map

import { createContext, useContext, useState, type ReactNode } from "react";

type TabsState = { activeTab: string; setActiveTab: (id: string) => void };
const TabsContext = createContext<TabsState | null>(null);

Build a Tabs component whose parts talk through context instead of cloning and inspecting children, so consumers can nest and reorder freely.

Reactintermediate

useId for stable, SSR-safe unique ids

import { useId } from "react";

export const PasswordField = () => {
  const id = useId();

Generate ids that match between server and client render, so aria-describedby and label associations survive hydration without a mismatch.

Reactadvanced

Suspense data fetching with a thrown promise cache

type Resource<T> = { read: () => T };

const cache = new Map<string, Resource<unknown>>();

export const getResource = <T,>(key: string, fetchData: () => Promise<T>): Resource<T> => {

Build the tiny promise cache that makes Suspense-based data fetching work: throw while pending, cache the result, return it once resolved.

Reactintermediate

Portals for rendering a modal outside the DOM hierarchy

import { useEffect, useState, type ReactNode } from "react";
import { createPortal } from "react-dom";

export const Modal = ({ children, onClose }: { children: ReactNode; onClose: () => void }) => {
  const [container] = useState(() => document.createElement("div"));

Render a modal into its own DOM node with createPortal, so its stacking context and layout escape a clipped or transformed ancestor.

Reactintermediate

A 10-line useDebouncedValue custom hook

import { useState, useEffect } from "react";

export const useDebouncedValue = <T,>(value: T, delayMs: number): T => {
  const [debounced, setDebounced] = useState(value);

Debounce a fast-changing value, like search input, without redefining a timer effect in every component that needs one.

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.

Reactadvanced

Context selector pattern to stop re-rendering every consumer

import { createContext, useContext, useSyncExternalStore } from "react";

type State = { count: number; user: { name: string } };
type Listener = () => void;

Build a selector hook on useSyncExternalStore so components only re-render when the slice of context state they read actually changes.

Reactintermediate

useLayoutEffect vs useEffect: measuring the DOM before paint

import { useRef, useState, useLayoutEffect } from "react";

export const Tooltip = ({ text }: { text: string }) => {
  const [height, setHeight] = useState(0);
  const ref = useRef<HTMLDivElement>(null);

Use useLayoutEffect to measure a DOM node and apply the result before the browser paints, avoiding the flicker useEffect leaves behind.

Reactintermediate

React.lazy + Suspense with an error boundary fallback

import { lazy, Suspense, Component, type ReactNode } from "react";

// In a real app, SettingsPanelImpl would live in its own file and this
// would be lazy(() => import("./SettingsPanel")) instead -- this snippet
// is one self-contained file, so it wraps an inline component the same

Code-split a component with React.lazy and catch its load failures with an error boundary, so a flaky chunk load does not blank the page.

Reactadvanced

useImperativeHandle to expose an imperative API via ref

import { useRef, useImperativeHandle, type Ref } from "react";

export type VideoHandle = { play: () => void; pause: () => void; seekTo: (seconds: number) => void };

export const VideoPlayer = ({ src, ref }: { src: string; ref?: Ref<VideoHandle> }) => {

Expose a small, deliberate imperative API (play, pause, seekTo) from a component, instead of leaking raw DOM nodes through a ref.

Reactintermediate

React.memo with a custom comparator for deep-equal props

import { memo } from "react";

type Props = { user: { id: string; name: string; tags: string[] } };

const isEqual = (prev: Props, next: Props) =>

Skip re-renders when props are structurally equal but not referentially equal, using memo second argument instead of a deep-equal library.

Reactintermediate

useTransition to keep input responsive during expensive updates

import { useState, useTransition } from "react";

export const FilterableList = ({ items }: { items: string[] }) => {
  const [text, setText] = useState("");
  const [visible, setVisible] = useState(items);

Mark an expensive state update as a transition so React keeps typing responsive and only shows the update once it is ready.

Reactintermediate

useDeferredValue for a jank-free typeahead search

import { useState, useDeferredValue, useMemo } from "react";

const filterItems = (items: string[], query: string) =>
  items.filter((item) => item.toLowerCase().includes(query.toLowerCase()));

Defer expensive list re-renders behind fast keystrokes with useDeferredValue, and show a stale-content hint while it catches up.

Reactadvanced

useSyncExternalStore for tearing-free external store subscriptions

import { useSyncExternalStore } from "react";

const EVENTS = ["online", "offline"] as const;

const subscribe = (onStoreChange: () => void) => {

Subscribe a component to state that lives outside React, like navigator.onLine, without ever showing a torn snapshot mid-render.