React Best Practices: A Comprehensive Guide
Executive Summary & Abstract
React remains one of the most widely adopted JavaScript libraries for building user interfaces, especially single-page applications (SPAs) that demand a responsive, dynamic user experience. As React applications grow in size and complexity, adherence to well-established best practices becomes critical for performance, maintainability, scalability, and developer velocity.
This guide expands on the fundamentals of React architecture and dives deeper into component design, state management strategies (local, lifted, global, and server state), performance optimization techniques, TypeScript integration, error handling, accessibility, folder structure conventions, and testing strategies — each backed by runnable code. It closes with an expanded trade-off matrix and a master checklist developers can use as a working reference during code review.
1. Component Architecture
1.1 Functional Components as the Default
Functional components paired with Hooks are the standard in modern React (16.8+). They are easier to test, avoid the confusion of this binding, and compose more naturally.
// Preferred: functional component
function UserCard({ name, role }) {
return (
<div className="user-card">
<h3>{name}</h3>
<p>{role}</p>
</div>
);
}
javascriptClass components are still valid for legacy codebases or when using error boundaries (which currently require a class-based implementation — see Section 5), but new code should default to function components.
1.2 Naming and File Organization
- PascalCase for component names and their files (
UserCard.jsx, notuserCard.jsx). - camelCase for hooks, utility functions, and variables (
useAuth,formatDate). - One component per file, with the file name matching the exported component name, to keep imports predictable.
1.3 Composition Over Inheritance
React explicitly favors composition. Instead of extending components, wrap and combine them:
function Card({ children, className = '' }) {
return <div className={`card ${className}`}>{children}</div>;
}
function ProfileCard({ user }) {
return (
<Card className="profile-card">
<Avatar src={user.avatarUrl} />
<h3>{user.name}</h3>
</Card>
);
}
javascriptThis pattern (sometimes called the "slot" or "children as props" pattern) keeps components flexible without deep prop-drilling or fragile inheritance chains.
1.4 Keeping Components Small and Focused
A component should ideally do one thing: render UI, manage a small piece of local state, or coordinate a handful of children. When a component's JSX exceeds roughly 150–200 lines, or its useEffect/useState count grows past 4–5, it's usually a sign to extract subcomponents or custom hooks.
2. Props, State, and Data Flow
2.1 Props: Read-Only Contracts
Props should never be mutated inside a child. If a child needs to change data passed down, it should call a callback prop supplied by the parent (unidirectional data flow):
function Counter({ count, onIncrement }) {
return <button onClick={onIncrement}>Count: {count}</button>;
}
function Parent() {
const [count, setCount] = useState(0);
return <Counter count={count} onIncrement={() => setCount(c => c + 1)} />;
}
javascript2.2 Local State vs. Lifted State vs. Global State
State Type When to Use Tooling Local state State only one component (and its direct children) cares about useState, useReducer Lifted state Two or more sibling components need to share/sync state Lift to nearest common parent Global/app state State needed across distant, unrelated parts of the tree Context API, Zustand, Redux Toolkit, Jotai Server state Data fetched from an API, with caching/revalidation needs TanStack Query (React Query), SWR
A common anti-pattern is reaching for a global state library to solve what is really a prop-drilling problem two or three levels deep — often useContext combined with useReducer is sufficient before introducing an external dependency.
2.3 useReducer for Complex State Logic
When state transitions depend on the previous state or involve multiple sub-values, useReducer produces more predictable, testable code than several interdependent useState calls:
function reducer(state, action) {
switch (action.type) {
case 'increment':
return { count: state.count + 1 };
case 'decrement':
return { count: state.count - 1 };
case 'reset':
return { count: 0 };
default:
throw new Error(`Unknown action: ${action.type}`);
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</>
);
}
javascript3. Hooks in Depth
3.1 useEffect — Rules and Pitfalls
- Always declare the dependency array, and keep it accurate; omitting dependencies is a common source of stale-closure bugs.
- Never call hooks conditionally — hooks must run in the same order on every render.
- Return a cleanup function whenever the effect subscribes to something (event listeners, sockets, timers).
function ChatRoom({ roomId }) {
useEffect(() => {
const connection = createConnection(roomId);
connection.connect();
return () => connection.disconnect(); // cleanup on unmount or roomId change
}, [roomId]);
return <div>Connected to {roomId}</div>;
}
javascript3.2 Custom Hooks for Reusable Logic
Custom hooks let you extract stateful logic without changing component hierarchy — arguably the single highest-leverage refactor available in a React codebase:
function useDebouncedValue(value, delayMs = 300) {
const [debounced, setDebounced] = useState(value);
useEffect(() => {
const handle = setTimeout(() => setDebounced(value), delayMs);
return () => clearTimeout(handle);
}, [value, delayMs]);
return debounced;
}
// Usage
function SearchBox() {
const [query, setQuery] = useState('');
const debouncedQuery = useDebouncedValue(query, 400);
useEffect(() => {
if (debouncedQuery) fetchResults(debouncedQuery);
}, [debouncedQuery]);
return <input value={query} onChange={e => setQuery(e.target.value)} />;
}
javascript3.3 useMemo and useCallback
Use these to preserve referential equality across renders — important when passing values/functions to memoized children or as effect dependencies. They are not a general-purpose performance switch; overusing them can add overhead without benefit.
const expensiveResult = useMemo(() => computeExpensive(items), [items]);
const stableHandler = useCallback(() => onSelect(item.id), [item.id, onSelect]);
javascript3.4 useRef for Mutable, Non-Rendering Values
useRef holds a mutable value that persists across renders without triggering a re-render — useful for DOM references, timers, and previous-value tracking:
function usePrevious(value) {
const ref = useRef();
useEffect(() => { ref.current = value; });
return ref.current;
}
javascript4. Performance Optimization
4.1 Memoization
React.memo prevents a functional component from re-rendering when its props haven't changed (shallow comparison):
const ListItem = React.memo(function ListItem({ item }) {
return <li>{item.label}</li>;
});
javascript4.2 Code Splitting and Lazy Loading
Split large bundles at route or feature boundaries using React.lazy and Suspense:
const Dashboard = React.lazy(() => import('./Dashboard'));
function App() {
return (
<Suspense fallback={<p>Loading dashboard...</p>}>
<Dashboard />
</Suspense>
);
}
javascript4.3 Virtualization for Long Lists
Rendering thousands of DOM nodes at once tanks performance regardless of memoization. Libraries like react-window or react-virtuoso render only the visible slice of a list:
import { FixedSizeList } from 'react-window';
function VirtualList({ items }) {
const Row = ({ index, style }) => (
<div style={style}>{items[index].label}</div>
);
return (
<FixedSizeList height={400} itemCount={items.length} itemSize={35} width="100%">
{Row}
</FixedSizeList>
);
}
javascript4.4 Avoiding Common Re-render Traps
- Don't create new object/array/function literals inline as props to memoized children (
<Child options={{ a: 1 }} />creates a new object every render). - Split state so that unrelated UI doesn't re-render together — e.g., keep a modal's open/closed state out of a component that also holds a large data table's state.
- Use the React DevTools Profiler to measure before optimizing; intuition about "what's slow" is frequently wrong.
5. Error Handling
5.1 Error Boundaries
Error boundaries catch rendering errors in their child tree and display a fallback UI instead of crashing the whole app. As of React 18, this must still be a class component (no hook equivalent exists yet):
class ErrorBoundary extends React.Component {
state = { hasError: false };
static getDerivedStateFromError() {
return { hasError: true };
}
componentDidCatch(error, info) {
logErrorToService(error, info);
}
render() {
if (this.state.hasError) return <FallbackUI />;
return this.props.children;
}
}
javascript5.2 Handling Async Errors
Error boundaries do not catch errors in event handlers or async code (e.g., inside a fetch callback). Handle those explicitly with try/catch and local error state, or via a data-fetching library that models error states for you (see Section 7).
6. TypeScript with React
Typed props catch entire classes of bugs at compile time:
interface UserCardProps {
name: string;
role: string;
onSelect?: (id: string) => void;
}
const UserCard: React.FC<UserCardProps> = ({ name, role, onSelect }) => (
<div onClick={() => onSelect?.(name)}>
<h3>{name}</h3>
<p>{role}</p>
</div>
);
typescriptBest practices:
- Prefer
interfacefor props (extensible via declaration merging); usetypefor unions and utility compositions. - Avoid
React.FCif you need flexible children typing in newer React versions — many teams now type props directly and skipReact.FCentirely. - Type
useStateexplicitly when the initial value doesn't convey the full type:useState<User | null>(null).
7. Server State and Data Fetching
Treat data fetched from an API as a distinct category from local UI state — it needs caching, deduplication, background refetching, and loading/error states. Libraries like TanStack Query remove large amounts of boilerplate:
import { useQuery } from '@tanstack/react-query';
function UserProfile({ userId }) {
const { data, isLoading, error } = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json()),
});
if (isLoading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
return <Profile user={data} />;
}
javascriptThis avoids the common anti-pattern of manually managing loading/error/data state with useEffect in every component that fetches data.
8. Accessibility (a11y)
- Use semantic HTML elements (
<button>,<nav>,<main>) instead of<div>with click handlers wherever possible. - Ensure interactive elements are keyboard-navigable (
tabIndex, visible focus states). - Provide
alttext for images andaria-labels for icon-only buttons. - Test with automated tools (
eslint-plugin-jsx-a11y, axe DevTools) as part of CI, not as an afterthought.
9. Real-World Application: To-Do List
9.1 Project Setup
npm create vite@latest todo-app -- --template react-ts
cd todo-app
npm install
npm run dev
bash9.2 Component Breakdown
types.ts
export interface Todo {
id: number;
text: string;
completed: boolean;
}
typescriptTodoItem.tsx
interface TodoItemProps {
todo: Todo;
onToggle: (id: number) => void;
onRemove: (id: number) => void;
}
function TodoItem({ todo, onToggle, onRemove }: TodoItemProps) {
return (
<li>
<input
type="checkbox"
checked={todo.completed}
onChange={() => onToggle(todo.id)}
/>
<span style={{ textDecoration: todo.completed ? 'line-through' : 'none' }}>
{todo.text}
</span>
<button onClick={() => onRemove(todo.id)} aria-label={`Delete ${todo.text}`}>
Delete
</button>
</li>
);
}
typescriptAddTodo.tsx
function AddTodo({ onAdd }: { onAdd: (text: string) => void }) {
const [text, setText] = useState('');
const handleSubmit = (e: React.FormEvent) => {
e.preventDefault();
const trimmed = text.trim();
if (!trimmed) return;
onAdd(trimmed);
setText('');
};
return (
<form onSubmit={handleSubmit}>
<input value={text} onChange={e => setText(e.target.value)} placeholder="Add a task" />
<button type="submit">Add</button>
</form>
);
}
typescriptApp.tsx
function App() {
const [todos, setTodos] = useState<Todo[]>([]);
const addTodo = (text: string) =>
setTodos(prev => [...prev, { id: Date.now(), text, completed: false }]);
const toggleTodo = (id: number) =>
setTodos(prev => prev.map(t => (t.id === id ? { ...t, completed: !t.completed } : t)));
const removeTodo = (id: number) =>
setTodos(prev => prev.filter(t => t.id !== id));
return (
<main>
<h1>To-Do List</h1>
<AddTodo onAdd={addTodo} />
<ul>
{todos.map(todo => (
<TodoItem key={todo.id} todo={todo} onToggle={toggleTodo} onRemove={removeTodo} />
))}
</ul>
</main>
);
}
typescriptNote the use of functional state updates (setTodos(prev => ...)) rather than reading todos directly from closure — this avoids stale-state bugs when multiple updates can queue in the same tick.
10. Testing Strategies
10.1 Unit Tests (Jest + React Testing Library)
import { render, screen, fireEvent } from '@testing-library/react';
import TodoItem from './TodoItem';
test('calls onToggle when checkbox is clicked', () => {
const todo = { id: 1, text: 'Buy milk', completed: false };
const onToggle = jest.fn();
render(<TodoItem todo={todo} onToggle={onToggle} onRemove={() => {}} />);
fireEvent.click(screen.getByRole('checkbox'));
expect(onToggle).toHaveBeenCalledWith(1);
});
javascript10.2 Integration Tests
Test components together rather than mocking every child — this catches wiring bugs that isolated unit tests miss:
test('adds a new todo and displays it', () => {
render(<App />);
fireEvent.change(screen.getByPlaceholderText('Add a task'), { target: { value: 'Walk dog' } });
fireEvent.click(screen.getByText('Add'));
expect(screen.getByText('Walk dog')).toBeInTheDocument();
});
javascript10.3 End-to-End Tests
Tools like Playwright or Cypress exercise the full stack in a real browser, catching issues unit/integration tests can't (routing, real network calls, browser quirks). These are slower and should cover critical user flows, not every edge case.
11. Folder Structure Conventions
For small apps, a flat structure works. For larger apps, feature-based ("colocation") structure scales better than type-based grouping:
src/
features/
todos/
TodoList.tsx
TodoItem.tsx
AddTodo.tsx
useTodos.ts
types.ts
auth/
LoginForm.tsx
useAuth.ts
shared/
components/
Button.tsx
Card.tsx
hooks/
useDebouncedValue.ts
App.tsx
cssGrouping by feature keeps related files near each other and makes it easier to delete or move an entire feature without hunting across a components/, hooks/, utils/ split.
12. Expanded Trade-off Analysis
Practice Advantages Disadvantages When to Skip Functional components + Hooks Simpler mental model, easier testing, better composition Some patterns (error boundaries) still need classes Rarely — near-universal default React.memo / useMemo / useCallback Fewer re-renders, referential stability Added complexity, risk of stale closures, memory overhead Skip on cheap components or when profiler shows no benefit Code splitting (React.lazy) Smaller initial bundle, faster first paint Extra network waterfall, requires Suspense boundaries Very small apps with negligible bundle size Global state libraries (Redux/Zustand) Predictable, centralized, good devtools Boilerplate (Redux), added dependency, learning curve When Context + useReducer already covers the need Server-state libraries (React Query/SWR) Built-in caching, retries, dedup Another dependency, learning curve for cache invalidation Apps with only a couple of simple, rarely-changing API calls TypeScript Compile-time safety, better autocomplete, self-documenting Build setup, initial learning curve, verbose generics Rapid prototypes/throwaway scripts Virtualized lists Handles thousands of rows smoothly Extra dependency, more complex row measurement logic Lists that are always short (under ~100 items) E2E tests Highest confidence, catches real integration bugs Slow, flaky if not maintained, expensive to run in CI Skip for internal tools with low risk tolerance
13. Master Study Checklist
Component Design
- Functional components + Hooks used by default
- Components composed via
children, not deep inheritance - Each component has a single, clear responsibility
- Props typed (TypeScript) or documented (PropTypes/JSDoc)
State Management
- Local state kept local; lifted only as far as necessary
-
useReducerused for multi-step or interdependent state transitions - Server state handled by a dedicated library, not raw
useEffectfetch patterns - No unnecessary global state for data only one feature uses
Performance
-
React.memo/useMemo/useCallbackapplied only where profiling shows benefit - Long lists virtualized
- Routes/heavy features code-split with
React.lazy+Suspense - No inline object/array/function literals passed to memoized children
Error Handling & Resilience
- Error boundaries wrap major UI sections
- Async errors caught and surfaced to the user, not swallowed
- Loading and empty states designed, not just the happy path
Accessibility
- Semantic HTML used over generic
<div>s - Keyboard navigation verified for interactive elements
- Automated a11y linting included in CI
Testing
- Unit tests for individual components/hooks
- Integration tests for key user flows
- E2E tests for critical paths (checkout, auth, etc.)
Code Quality
- ESLint + Prettier enforced, ideally via pre-commit hook
- Consistent naming and folder structure across the codebase
- Regular code review with a checklist, not just ad hoc comments
Conclusion
React's flexibility is both its greatest strength and its biggest risk — the library imposes few hard rules, which means architectural discipline has to come from the team. The practices above — composition over inheritance, careful state placement, targeted (not blanket) memoization, dedicated server-state tooling, and a layered testing strategy — form a working baseline that scales from a small to-do app to a large production codebase without requiring a rewrite along the way.

