Reactintermediate
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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
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.