📡 You're offline — showing cached content
New version available!
Quick Access
React.js Reference

React.js Hooks

Components, useState, useEffect, and modern patterns.

All Topics

Components & JSX

Function components
Modern React — plain JS functions returning JSX. Hooks only work in function components.
Example: export default function Card({ title, children }) { return <div className="card"><h2>{title}</h2>{children}</div>; }
JSX expressions {}
Any JS expression inside {}. Use ternary and && for conditionals. Never use if/else directly.
Example: {isLoggedIn ? <Dashboard/> : <Login/>} | {count > 0 && <Badge n={count}/>}
key prop in lists
Stable, unique key helps React identify changed items. Use data IDs, never array indexes.
Example: {posts.map(p => <Post key={p.id} data={p}/>)}
Fragment <>...</>
Group elements without adding DOM nodes. Keyed fragments with <Fragment key> in lists.
Example: return <><li>First</li><li>Second</li></>;
Portal: createPortal
Render children into a different DOM node — modals, tooltips, dropdowns outside parent overflow.
Example: return createPortal(<Modal/>, document.getElementById('modal-root'));
Error boundaries
Class component that catches render/lifecycle errors in subtree — show fallback UI gracefully.
Example: class EB extends React.Component { componentDidCatch(e,i){log(e)} render(){ return this.state.err ? <Fallback/> : this.props.children } }
Compound components
Components that work together (like Select + Option) sharing state via Context.
Example: <Tabs><Tabs.List><Tabs.Tab>One</Tabs.Tab></Tabs.List><Tabs.Panel>Content</Tabs.Panel></Tabs>

Core Hooks

useState(init)
Returns [state, setState]. Functional updates (fn(prev)=>) prevent stale closure bugs with async.
Example: const [count, setCount] = useState(0); setCount(prev => prev + 1);
useEffect(fn, deps)
Sync with external systems. [] = run once (mount). No deps = every render. Return fn to cleanup.
Example: useEffect(() => { const sub = store.subscribe(update); return () => sub.unsubscribe(); }, [store]);
useRef(initial)
Mutable object persisting across renders without causing re-renders. DOM refs or previous values.
Example: const prevProps = useRef(props); useEffect(() => { prevProps.current = props; });
useCallback(fn, deps)
Memoize function reference — prevents child re-renders when passing stable callbacks.
Example: const handleClick = useCallback(() => dispatch({type:'INC'}), [dispatch]);
useMemo(fn, deps)
Memoize expensive computed values. Recalculates only when deps change.
Example: const sorted = useMemo(() => [...items].sort(cmp), [items]);
useReducer(reducer, init)
Better than useState for complex state machines with multiple sub-values and related transitions.
Example: const [state, dispatch] = useReducer(reducer, {count:0, status:'idle'});
useContext(Context)
Consume context value without prop-drilling. Component re-renders when context value changes.
Example: const { user, logout } = useContext(AuthContext);
useId()
Generate unique stable IDs — for label/input associations in components that render multiple times.
Example: const id = useId(); return <><label htmlFor={id}>Name</label><input id={id}/></>;

Advanced Hooks & Patterns

useTransition / useDeferredValue
Mark state updates as non-urgent — keep UI responsive during heavy renders (search, filter).
Example: const [isPending, startTransition] = useTransition(); startTransition(() => setFilter(input));
useImperativeHandle + forwardRef
Expose custom methods from a child component to parent via ref.
Example: useImperativeHandle(ref, () => ({ focus: () => inputRef.current.focus() }));
useSyncExternalStore
Subscribe to external stores with SSR support — for Redux, Zustand, browser APIs.
Example: const width = useSyncExternalStore(store.subscribe, store.getSnapshot, store.getServerSnapshot);
React.memo(Component)
Memoize component — skip re-render if props haven't changed. Second arg for custom comparison.
Example: const List = React.memo(({ items }) => ..., (prev, next) => deepEqual(prev.items, next.items));
Custom hooks convention
Extract stateful logic into functions starting with "use". Hooks can call other hooks.
Example: function useLocalStorage(key, init) { const [v, setV] = useState(() => JSON.parse(localStorage.getItem(key)) ?? init); ... }
Suspense + lazy()
Code-split components — load on demand. Suspense shows fallback while loading asynchronously.
Example: const Chart = lazy(() => import('./Chart')); <Suspense fallback={<Spinner/>}><Chart/></Suspense>
use() hook (React 19)
Read resource (Promise or Context) in render — works in Server Components and Suspense boundaries.
Example: const user = use(fetchUserPromise); // suspends while pending

State Management

Context + useReducer
Lightweight global state without a library. Provider holds dispatch; consumers access state + actions.
Example: const StateCtx = createContext(); export const useStore = () => useContext(StateCtx);
Zustand pattern
Minimal flux-like state. create() defines store with state and actions together.
Example: const useStore = create(set => ({ count: 0, inc: () => set(s => ({count: s.count+1})) }));
Lifting state up
Move state to the nearest common ancestor when siblings need to share it.
Example: // Parent: const [tab, setTab] = useState(); // Pass setTab to child A, tab to child B
Derived state (selector)
Compute derived data from state in render or useMemo — avoid storing derived data in state.
Example: const totalPrice = useMemo(() => cart.reduce((s,i) => s+i.price, 0), [cart]);
Optimistic UI updates
Update state immediately before server confirms — revert on error for responsive feel.
Example: setItems(prev => [...prev, optimistic]); await api.save(); // revert in catch
React Query / TanStack Query
Server state management — fetching, caching, background sync, stale-while-revalidate.
Example: const { data, isLoading } = useQuery({ queryKey: ['post', id], queryFn: () => fetchPost(id) });

Performance & Testing

Profiler component
Measure rendering cost of component subtrees. onRender callback receives timing data.
Example: <Profiler id="Nav" onRender={(id,phase,actual) => console.log(id,actual)}><Nav/></Profiler>
Why did you Render (dev)
@welldone-software/why-did-you-render tracks and logs avoidable re-renders in development.
Example: MyComp.whyDidYouRender = true; // logs every unnecessary re-render
React Testing Library
Test from user's perspective — findByRole, findByText, userEvent. Avoid testing implementation.
Example: const btn = screen.getByRole('button', {name: /submit/i}); await userEvent.click(btn);
act() wrapper
Wrap state-updating test code in act() to flush effects and state updates before asserts.
Example: await act(async () => { await userEvent.click(submitBtn); });