The Ultimate React Cheatsheet
The Ultimate React Cheatsheet
React remains the dominant library for building user interfaces. Whether you're a beginner learning the ropes or a senior developer needing a quick reference, this cheatsheet covers the core concepts, modern hooks, and component patterns you use every day.
React Hooks Cheat Sheet
Hooks allow you to use state and other React features without writing a class.
useState: Manage local component state.useEffect: Perform side effects (data fetching, subscriptions).useContext: Access values from a React context.useRef: Persist values across renders without triggering a re-render, or access DOM elements directly.useMemo: Memoize expensive calculations so they don't re-run on every render.useCallback: Memoize a function definition to prevent unnecessary child re-renders.useReducer: Manage complex state logic (similar to Redux).
useState Examples
The most fundamental hook for adding reactivity to your UI.
import { useState } from 'react';
export default function Counter() {
// 1. Basic state
const [count, setCount] = useState(0);
// 2. Object state
const [user, setUser] = useState({ name: 'Alice', age: 25 });
// 3. Array state
const [items, setItems] = useState(['Apple', 'Banana']);
return (
<div>
{/* Updating basic state (using updater function for safety) */}
<button onClick={() => setCount(prev => prev + 1)}>
Count: {count}
</button>
{/* Updating object state (spread previous state) */}
<button onClick={() => setUser({ ...user, age: 26 })}>
Happy Birthday {user.name}!
</button>
{/* Updating array state (create a new array) */}
<button onClick={() => setItems([...items, 'Cherry'])}>
Add Cherry
</button>
</div>
);
}useEffect Guide
useEffect handles side effects. Its behavior changes based on the dependency array.
import { useEffect, useState } from 'react';
export default function DataFetcher({ userId }) {
const [data, setData] = useState(null);
// 1. No dependency array: Runs after EVERY render
useEffect(() => {
console.log('I run after every render!');
});
// 2. Empty array []: Runs ONCE on mount
useEffect(() => {
console.log('Component mounted');
// Cleanup function: Runs on unmount
return () => console.log('Component unmounted');
}, []);
// 3. With dependencies: Runs on mount AND when `userId` changes
useEffect(() => {
let ignore = false; // Prevent race conditions
async function fetchUser() {
const response = await fetch(`/api/users/${userId}`);
const json = await response.json();
if (!ignore) setData(json);
}
fetchUser();
return () => {
ignore = true; // Cleanup running fetch if userId changes quickly
};
}, [userId]); // Re-run if userId changes
return <div>{data ? data.name : 'Loading...'}</div>;
}Context API
Avoid "prop drilling" by sharing state globally across your component tree.
import { createContext, useContext, useState } from 'react';
// 1. Create the Context
const ThemeContext = createContext('light');
// 2. Create a Provider Component
export function ThemeProvider({ children }) {
const [theme, setTheme] = useState('light');
return (
<ThemeContext.Provider value={{ theme, setTheme }}>
{children}
</ThemeContext.Provider>
);
}
// 3. Consume the Context anywhere in the tree
export function ThemedButton() {
const { theme, setTheme } = useContext(ThemeContext);
return (
<button
onClick={() => setTheme(theme === 'light' ? 'dark' : 'light')}
style={{ background: theme === 'light' ? '#fff' : '#000' }}
>
Toggle Theme
</button>
);
}React Lifecycle
While class components have explicit lifecycle methods (componentDidMount, componentDidUpdate, componentWillUnmount), functional components map these concepts to hooks.
- Mounting: When the component is first added to the DOM.
- Class:
constructor→render→componentDidMount - Functional: Component function runs → DOM updates →
useEffect(..., [])runs.
- Class:
- Updating: When props or state change.
- Class:
render→componentDidUpdate - Functional: Component function runs → DOM updates →
useEffect(..., [deps])runs.
- Class:
- Unmounting: When the component is removed from the DOM.
- Class:
componentWillUnmount - Functional: The cleanup function returned from
useEffectruns.
- Class:
React Event Handling
React uses a synthetic event system, which normalizes events across different browsers.
export default function FormExample() {
// Prevent default form submission behavior
const handleSubmit = (e: React.FormEvent<HTMLFormElement>) => {
e.preventDefault();
console.log('Form submitted!');
};
// Handle input changes
const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
console.log('New value:', e.target.value);
};
return (
<form onSubmit={handleSubmit}>
<input type="text" onChange={handleChange} />
<button type="submit">Submit</button>
{/* Stop event propagation (bubbling) */}
<button type="button" onClick={(e) => e.stopPropagation()}>
Click me (Won't bubble)
</button>
</form>
);
}Component Patterns
Modern patterns for building robust and reusable React components.
1. Composition (Container & Presentational)
Separate data fetching (Container) from UI rendering (Presentational).
// Presentational (Dumb)
const UserProfile = ({ user }) => <h1>{user.name}</h1>;
// Container (Smart)
const UserProfileContainer = ({ id }) => {
const user = useFetchUser(id);
return <UserProfile user={user} />;
};2. Custom Hooks
Extract stateful logic into reusable functions.
function useWindowWidth() {
const [width, setWidth] = useState(window.innerWidth);
useEffect(() => {
const handleResize = () => setWidth(window.innerWidth);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return width;
}3. Higher-Order Components (HOCs) / Render Props
While largely replaced by Custom Hooks, you may still see them. They wrap components to inject props or share logic.
// A pattern for passing components as children (Slot pattern)
const Card = ({ header, children, footer }) => (
<div className="card">
<div className="card-header">{header}</div>
<div className="card-body">{children}</div>
<div className="card-footer">{footer}</div>
</div>
);Read Next
The Ultimate AI & LangChain Cheatsheet
A comprehensive guide to AI development with LangChain and OpenAI. Master prompt engineering, RAG, agents, embeddings, and vector databases.
The Ultimate Deployment Cheatsheet
A comprehensive guide to deploying web apps. Master Vercel, VPS setup, Nginx, environment variables, domain configuration, and SSL certificates.