Web Development49 entries

React Hooks

useState, useEffect, useRef, useMemo, React 19 hooks, and custom hook patterns

1State Hooks

const [value, setValue] = useState(initial)
Declare state variable with initial value
setValue(newValue)
Replace state with new value
setValue(prev => prev + 1)
Update state based on previous value
useState(() => expensiveComputation())
Lazy initialization (runs once)
const [state, dispatch] = useReducer(reducer, init)
State with reducer pattern
dispatch({ type: "INCREMENT" })
Dispatch action to reducer
useReducer(reducer, arg, createInit)
Lazy reducer initialization

2Effect Hooks

useEffect(() => { ... })
Run effect after every render
useEffect(() => { ... }, [])
Run effect once on mount
useEffect(() => { ... }, [dep])
Run effect when dep changes
useEffect(() => { return () => cleanup(); }, [])
Cleanup on unmount
useLayoutEffect(() => { ... })
Run synchronously after DOM mutations
useInsertionEffect(() => { ... })
Inject styles before layout (CSS-in-JS)

3Ref Hooks

const ref = useRef(null)
Create mutable ref object
ref.current
Access current ref value
<input ref={ref} />
Attach ref to DOM element
const countRef = useRef(0)
Store value without re-renders
useImperativeHandle(ref, () => ({ focus }))
Customize ref exposed to parent
forwardRef((props, ref) => <input ref={ref} />)
Forward ref to child component

4Context Hook

const ctx = createContext(defaultValue)
Create a context object
<MyContext.Provider value={data}>
Provide context value to children
const value = useContext(MyContext)
Consume nearest context value
useContext(ThemeContext) ?? "light"
Fallback for missing provider

5Performance Hooks

const memoized = useMemo(() => compute(a, b), [a, b])
Memoize expensive computation
const handler = useCallback((e) => { ... }, [dep])
Memoize callback function
const [isPending, startTransition] = useTransition()
Mark state update as non-urgent
startTransition(() => setSearchQuery(input))
Defer a non-urgent update
const deferredValue = useDeferredValue(value)
Defer re-render for a value
memo(Component)
Skip re-render if props unchanged

6React 19 Hooks

const data = use(promise)
Unwrap promise or context
const [state, action, isPending] = useActionState(fn, init)
Form action with pending state
const [optimistic, setOptimistic] = useOptimistic(state)
Optimistic UI updates
const { pending } = useFormStatus()
Form submission pending state
useId()
Generate unique ID for accessibility
useSyncExternalStore(subscribe, getSnapshot)
Subscribe to external data store

7Custom Hook Patterns

function useLocalStorage(key, init) { ... }
Persist state to localStorage
function useDebounce(value, delay) { ... }
Debounce rapidly changing values
function useFetch(url) { ... }
Data fetching with loading state
function useMediaQuery(query) { ... }
Respond to CSS media queries
function useClickOutside(ref, handler) { ... }
Detect clicks outside element
function usePrevious(value) { ... }
Track previous render value
function useInterval(callback, delay) { ... }
Declarative setInterval wrapper
function useToggle(initial = false) { ... }
Boolean toggle state

8Rules & Best Practices

Only call hooks at the top level
Never inside loops, conditions, or nested functions
Only call hooks from React functions
Components or custom hooks only
Name custom hooks with "use" prefix
useXxx naming convention required
List all dependencies in the array
Omitting deps causes stale closures
Avoid objects/arrays as deps (use primitives)
Reference equality causes extra runs
Cleanup effects to prevent memory leaks
Return cleanup function from useEffect