Essential troubleshooting, best practices, and performance optimization for React developers
These errors usually occur when dependencies are missing or incorrectly installed:
// โ Wrong: Conditional hook usage if (condition) { const [state, setState] = useState(); } // โ Correct: Hooks at top level const [state, setState] = useState(); if (condition) { // Use state here }
The traditional, battle-tested approach for React projects.
Pros: Zero configuration, stable, extensive documentation
Cons: Slower builds, less flexible, larger bundle
Modern, fast development server with instant HMR.
Pros: Lightning fast, modern tooling, smaller builds
Cons: Newer ecosystem, some plugins may not be compatible
Full-stack React framework with SSR and file-based routing.
Pros: SEO-friendly, full-stack features, great performance
Cons: More complex, opinionated structure
The most important tool for React debugging. Available as browser extensions for Chrome and Firefox.
// Add logging to understand state changes const [count, setCount] = useState(0); useEffect(() => { console.log('Count changed:', count); }, [count]); // Use React DevTools Profiler to identify re-renders const MyComponent = React.memo(function MyComponent(props) { console.log('MyComponent rendered', props); return <div>{props.children}</div>; });
// Use React.memo to prevent re-renders const ExpensiveComponent = React.memo(function ExpensiveComponent({ data }) { return <div>{data.map(item => <Item key={item.id} item={item} />)}</div>; }); // Use useMemo for expensive calculations const expensiveValue = useMemo(() => { return data.filter(item => item.active).length; }, [data]); // Use useCallback for event handlers const handleClick = useCallback((id) => { setSelectedId(id); }, []);
// Lazy load components const LazyComponent = React.lazy(() => import('./LazyComponent')); function App() { return ( <Suspense fallback={<div>Loading...</div>}> <LazyComponent /> </Suspense> ); } // Route-based code splitting const Home = React.lazy(() => import('./pages/Home')); const About = React.lazy(() => import('./pages/About'));
// Example component test import { render, screen, fireEvent } from '@testing-library/react'; import userEvent from '@testing-library/user-event'; import Counter from './Counter'; test('increments counter when button is clicked', async () => { const user = userEvent.setup(); render(<Counter />); const button = screen.getByRole('button', { name: /increment/i }); await user.click(button); expect(screen.getByText('Count: 1')) .toBeInTheDocument(); });