Introduction
As a React developer, you’ll often find yourself needing quick access to syntax, patterns, and best practices while coding. This chapter serves as your ultimate React Cheat Sheet – a comprehensive reference guide that consolidates all the essential React concepts, code snippets, and patterns you need at your fingertips. Whether you’re a beginner looking to memorize core concepts or an experienced developer seeking quick syntax reminders, this collection of cheat sheets covers everything from basic JSX and component patterns to advanced hooks, performance optimization techniques, and testing strategies. Keep this chapter bookmarked as your go-to resource for fast lookups, code examples, and proven patterns that will accelerate your React development workflow and help you write better, more efficient code.
React Component Cheat Sheet
Function Components
// Basic Function Component
function MyComponent() {
return <div>Hello World</div>;
}
// Arrow Function Component
const MyComponent = () => {
return <div>Hello World</div>;
}
// Component with Props
const Greeting = ({ name, age }) => {
return <div>Hello {name}, you are {age} years old</div>;
}
// Component with Default Props
const Button = ({ text = "Click me", onClick }) => {
return <button onClick={onClick}>{text}</button>;
}
Class Components
// Basic Class Component
class MyComponent extends React.Component {
render() {
return <div>Hello World</div>;
}
}
// Class Component with State
class Counter extends React.Component {
constructor(props) {
super(props);
this.state = { count: 0 };
}
increment = () => {
this.setState({ count: this.state.count + 1 });
}
render() {
return (
<div>
<p>Count: {this.state.count}</p>
<button onClick={this.increment}>Increment</button>
</div>
);
}
}
Component Lifecycle Methods
class LifecycleComponent extends React.Component {
// Mounting
componentDidMount() {
// Component mounted
}
// Updating
componentDidUpdate(prevProps, prevState) {
// Component updated
}
// Unmounting
componentWillUnmount() {
// Component will unmount
}
// Error Handling
componentDidCatch(error, errorInfo) {
// Handle error
}
}
JSX Syntax Reference
Basic JSX Rules
// JSX must return a single parent element
const Valid = () => (
<div>
<h1>Title</h1>
<p>Content</p>
</div>
);
// Use React.Fragment or <> for multiple elements
const Fragment = () => (
<>
<h1>Title</h1>
<p>Content</p>
</>
);
// Self-closing tags
const SelfClosing = () => <img src="image.jpg" alt="Description" />;
JSX Expressions
const name = "John";
const age = 30;
const isLoggedIn = true;
const JSXExpressions = () => (
<div>
{/* Variables */}
<h1>Hello {name}</h1>
{/* Expressions */}
<p>Age: {age + 5}</p>
{/* Conditional rendering */}
{isLoggedIn ? <p>Welcome!</p> : <p>Please log in</p>}
{/* Conditional rendering with && */}
{isLoggedIn && <p>You are logged in</p>}
{/* Array rendering */}
{[1, 2, 3].map(num => <span key={num}>{num}</span>)}
</div>
);
JSX Attributes
const AttributeExamples = () => (
<div>
{/* className instead of class */}
<div className="container">
{/* htmlFor instead of for */}
<label htmlFor="input">Label</label>
<input id="input" type="text" />
{/* camelCase for attributes */}
<div tabIndex="0" onClick={handleClick}>
{/* Style as object */}
<span style={{ color: 'red', fontSize: '16px' }}>
Styled text
</span>
</div>
</div>
</div>
);
React Hooks Quick Reference
useState
import { useState } from 'react';
const StateExample = () => {
const [count, setCount] = useState(0);
const [user, setUser] = useState({ name: '', email: '' });
const [items, setItems] = useState([]);
// Update state
const increment = () => setCount(count + 1);
const updateUser = () => setUser({ ...user, name: 'John' });
const addItem = () => setItems([...items, 'new item']);
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
</div>
);
};
useEffect
import { useEffect, useState } from 'react';
const EffectExample = () => {
const [data, setData] = useState(null);
// Run once on mount
useEffect(() => {
fetchData();
}, []);
// Run on every render
useEffect(() => {
console.log('Component rendered');
});
// Run when dependency changes
useEffect(() => {
updateData();
}, [data]);
// Cleanup function
useEffect(() => {
const timer = setInterval(() => {
console.log('Timer tick');
}, 1000);
return () => clearInterval(timer);
}, []);
return <div>Effect Example</div>;
};
useContext
import { createContext, useContext } from 'react';
const ThemeContext = createContext();
const ThemeProvider = ({ children }) => {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
};
const ThemedComponent = () => {
const { theme, setTheme } = useContext(ThemeContext);
return (
<div className={theme}>
<button onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}>
Toggle Theme
</button>
</div>
);
};
useReducer
import { useReducer } from 'react';
const 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:
return state;
}
};
const ReducerExample = () => {
const [state, dispatch] = useReducer(reducer, { count: 0 });
return (
<div>
<p>Count: {state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
<button onClick={() => dispatch({ type: 'decrement' })}>-</button>
<button onClick={() => dispatch({ type: 'reset' })}>Reset</button>
</div>
);
};
Custom Hooks
// Custom hook for local storage
const useLocalStorage = (key, initialValue) => {
const [storedValue, setStoredValue] = useState(() => {
try {
const item = window.localStorage.getItem(key);
return item ? JSON.parse(item) : initialValue;
} catch (error) {
return initialValue;
}
});
const setValue = (value) => {
try {
setStoredValue(value);
window.localStorage.setItem(key, JSON.stringify(value));
} catch (error) {
console.error(error);
}
};
return [storedValue, setValue];
};
// Custom hook for API calls
const useApi = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
setLoading(true);
const response = await fetch(url);
const result = await response.json();
setData(result);
} catch (err) {
setError(err);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
Event Handling Reference
Common Event Handlers
const EventHandlers = () => {
const handleClick = (e) => {
console.log('Button clicked');
e.preventDefault(); // Prevent default behavior
e.stopPropagation(); // Stop event bubbling
};
const handleChange = (e) => {
console.log('Input value:', e.target.value);
};
const handleSubmit = (e) => {
e.preventDefault();
const formData = new FormData(e.target);
console.log('Form data:', Object.fromEntries(formData));
};
const handleKeyPress = (e) => {
if (e.key === 'Enter') {
console.log('Enter key pressed');
}
};
return (
<div>
<button onClick={handleClick}>Click me</button>
<input onChange={handleChange} onKeyPress={handleKeyPress} />
<form onSubmit={handleSubmit}>
<input name="username" />
<button type="submit">Submit</button>
</form>
</div>
);
};
Event Types
// Mouse Events
onMouseDown, onMouseUp, onMouseMove, onMouseEnter, onMouseLeave
// Keyboard Events
onKeyDown, onKeyUp, onKeyPress
// Form Events
onChange, onSubmit, onFocus, onBlur
// Touch Events
onTouchStart, onTouchMove, onTouchEnd
// Drag Events
onDragStart, onDragOver, onDrop
React Router Cheat Sheet
Basic Router Setup
import { BrowserRouter, Routes, Route, Link, useNavigate } from 'react-router-dom';
const App = () => (
<BrowserRouter>
<nav>
<Link to="/">Home</Link>
<Link to="/about">About</Link>
<Link to="/contact">Contact</Link>
</nav>
<Routes>
<Route path="/" element={<Home />} />
<Route path="/about" element={<About />} />
<Route path="/contact" element={<Contact />} />
<Route path="/users/:id" element={<UserProfile />} />
<Route path="*" element={<NotFound />} />
</Routes>
</BrowserRouter>
);
Navigation Hooks
import { useNavigate, useParams, useLocation } from 'react-router-dom';
const NavigationExample = () => {
const navigate = useNavigate();
const params = useParams();
const location = useLocation();
const goToHome = () => navigate('/');
const goBack = () => navigate(-1);
return (
<div>
<p>Current path: {location.pathname}</p>
<p>User ID: {params.id}</p>
<button onClick={goToHome}>Go Home</button>
<button onClick={goBack}>Go Back</button>
</div>
);
};
State Management Patterns
Lifting State Up
// Parent component manages state
const Parent = () => {
const [count, setCount] = useState(0);
return (
<div>
<Child1 count={count} />
<Child2 onIncrement={() => setCount(count + 1)} />
</div>
);
};
const Child1 = ({ count }) => <div>Count: {count}</div>;
const Child2 = ({ onIncrement }) => <button onClick={onIncrement}>+</button>;
Context for Global State
const AppContext = createContext();
const AppProvider = ({ children }) => {
const [user, setUser] = useState(null);
const [theme, setTheme] = useState('light');
const login = (userData) => setUser(userData);
const logout = () => setUser(null);
return (
<AppContext.Provider value={{ user, theme, login, logout, setTheme }}>
{children}
</AppContext.Provider>
);
};
Performance Optimization Checklist
React.memo
const ExpensiveComponent = React.memo(({ data }) => {
 return <div>{/* Expensive rendering logic */}</div>;
});
// With custom comparison
const OptimizedComponent = React.memo(({ user }) => {
 return <div>{user.name}</div>;
}, (prevProps, nextProps) => {
 return prevProps.user.id === nextProps.user.id;
});
useMemo and useCallback
const OptimizedComponent = ({ items, filter }) => {
// Memoize expensive calculations
const filteredItems = useMemo(() => {
return items.filter(item => item.category === filter);
}, [items, filter]);
// Memoize callback functions
const handleClick = useCallback((id) => {
console.log('Clicked item:', id);
}, []);
return (
<div>
{filteredItems.map(item => (
<Item key={item.id} item={item} onClick={handleClick} />
))}
</div>
);
};
Code Splitting
import { lazy, Suspense } from 'react';
const LazyComponent = lazy(() => import('./LazyComponent'));
const App = () => (
 <Suspense fallback={<div>Loading...</div>}>
  <LazyComponent />
 </Suspense>
);
Testing Quick Reference
Jest Test Structure
describe('Component Name', () => {
 test('should render correctly', () => {
  // Test implementation
 });
 test('should handle user interaction', () => {
  // Test implementation
 });
});
React Testing Library
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
test('renders button and handles click', () => {
 const handleClick = jest.fn();
 render(<Button onClick={handleClick}>Click me</Button>);
Â
 const button = screen.getByText('Click me');
 expect(button).toBeInTheDocument();
Â
 fireEvent.click(button);
 expect(handleClick).toHaveBeenCalled();
});
Common Testing Queries
// Get by text
screen.getByText('Hello World');
// Get by role
screen.getByRole('button');
// Get by test id
screen.getByTestId('submit-button');
// Get by label text
screen.getByLabelText('Username');
// Query variants
screen.queryByText('Maybe exists'); // Returns null if not found
screen.findByText('Async content'); // Returns promise
Common Patterns and Best Practices
Component Composition
// Higher-Order Component
const withLoading = (Component) => {
 return ({ isLoading, ...props }) => {
  if (isLoading) return <div>Loading...</div>;
  return <Component {...props} />;
 };
};
// Render Props
const DataProvider = ({ children }) => {
 const [data, setData] = useState(null);
 return children({ data, setData });
};
// Usage
<DataProvider>
 {({ data, setData }) => (
  <div>
   {data ? <DisplayData data={data} /> : <LoadData onLoad={setData} />}
  </div>
 )}
</DataProvider>
Error Boundaries
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
return { hasError: true };
}
componentDidCatch(error, errorInfo) {
console.error('Error caught by boundary:', error, errorInfo);
}
render() {
if (this.state.hasError) {
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}
Debugging Commands
React DevTools
# Install React DevTools
npm install -g react-devtools
# Launch standalone DevTools
react-devtools
Console Debugging
// Debug renders
console.log('Component rendered with props:', props);
// Debug state changes
useEffect(() => {
 console.log('State changed:', state);
}, [state]);
// Debug performance
console.time('Expensive operation');
// ... expensive operation
console.timeEnd('Expensive operation');
Error Tracking
// Global error handler
window.addEventListener('unhandledrejection', (event) => {
 console.error('Unhandled promise rejection:', event.reason);
});
// React error boundary logging
const logError = (error, errorInfo) => {
 console.error('React Error:', error);
 console.error('Error Info:', errorInfo);
};
Useful React Libraries
UI Libraries
# Material-UI
npm install @mui/material @emotion/react @emotion/styled
# Ant Design
npm install antd
# Chakra UI
npm install @chakra-ui/react @emotion/react @emotion/styled
# React Bootstrap
npm install react-bootstrap bootstrap
State Management
# Redux Toolkit
npm install @reduxjs/toolkit react-redux
# Zustand
npm install zustand
# MobX
npm install mobx mobx-react-lite
Form Libraries
# React Hook Form
npm install react-hook-form
# Formik
npm install formik yup
Animation Libraries
# Framer Motion
npm install framer-motion
# React Spring
npm install @react-spring/web
ES6+ Features for React
Destructuring
// Array destructuring
const [first, second] = useState(0);
// Object destructuring
const { name, age } = props;
const { data, loading, error } = useApi('/api/users');
// Nested destructuring
const { user: { name, email } } = props;
Spread Operator
// Array spread
const newItems = [...items, newItem];
// Object spread
const newUser = { ...user, name: 'Updated Name' };
// Props spread
<Component {...props} additionalProp="value" />
Template Literals
const message = `Hello ${name}, you have ${count} messages`;
const className = `btn ${isActive ? 'active' : ''} ${size}`;
Arrow Functions
// Implicit return
const Component = () => <div>Hello</div>;
// With parameters
const handleClick = (id) => console.log(id);
// With multiple parameters
const handleSubmit = (data, options) => {
 // Handle submit
};
Async/Await
const fetchData = async () => {
 try {
  const response = await fetch('/api/data');
  const data = await response.json();
  setData(data);
 } catch (error) {
  setError(error);
 }
};
Optional Chaining
const name = user?.profile?.name;
const firstItem = items?.[0];
const callback = props?.onCallback?.();
Nullish Coalescing
const displayName = user.name ?? 'Anonymous';
const count = items.length ?? 0;
Summary
This chapter provides essential quick references for React development. Keep these cheat sheets handy for:
- Component patterns – Function and class components with common patterns
- JSX syntax – Rules and expressions for JSX
- Hooks reference – All built-in hooks with examples
- Event handling – Common event patterns and handlers
- Router navigation – React Router setup and navigation
- State management – Patterns for managing state
- Performance – Optimization techniques and patterns
- Testing – Common testing patterns and queries
- Best practices – Proven patterns and approaches
- Libraries – Essential React ecosystem libraries
- ES6+ features – Modern JavaScript features for React
These references will help you write better React code faster and serve as a quick lookup when you need to remember specific syntax or patterns.
Related Articles
- Chapter 1: Introduction to React JS
- Chapter 2: Setting Up the Development Environment for React
- Chapter 3: Basic JavaScript for React
- Chapter 4: Understanding JSX
- Chapter 5: React Components
- Chapter 6: State and Props
- Chapter 7: React DOM and Virtual DOM
- Chapter 8: Lifecycle Methods
- Chapter 9: Event Handling in React
- Chapter 10: State Management Basics
- Chapter 11: React Hooks
- Chapter 12: React Router
- Chapter 13: Optimization and Performance
- Chapter 14: Server Side Rendering
- Chapter 15: React Context API