React Cheatsheet
A quick-reference guide to modern React development, covering essential hooks, performance optimizations, and lifecycle mapping.
Core Hooks
1. useState
State management within a functional component.
const [count, setCount] = useState(0);
// Update using previous state
setCount(prev => prev + 1);
// Lazy initialization (only runs on first render)
const [data, setData] = useState(() => expensiveComputation());
2. useEffect
Handles side effects (API calls, subscriptions, DOM manipulation).
useEffect(() => {
// Setup (runs on mount and when dependencies change)
const subscription = api.subscribe();
// Cleanup (runs on unmount and before the next effect runs)
return () => {
subscription.unsubscribe();
};
}, [dependencyA, dependencyB]); // Dependency array
[]: Runs only once on mount.- No array: Runs on every single render.
3. useContext
Consume a React context without nesting <Context.Consumer>.
const theme = useContext(ThemeContext);
4. useRef
Mutable reference that persists across renders. Does not trigger re-renders.
const inputRef = useRef(null);
// Accessing DOM elements
<input ref={inputRef} />
inputRef.current.focus();
// Storing mutable values
const timerRef = useRef(null);
timerRef.current = setInterval(() => {}, 1000);
Performance Hooks
useMemo
Memoizes a computationally expensive value. Only recalculates if dependencies change.
const sortedList = useMemo(() => {
return list.sort((a, b) => a.value - b.value);
}, [list]);
useCallback
Memoizes a function definition to prevent unnecessary re-renders of child components that depend on it.
const handleClick = useCallback(() => {
console.log(id);
}, [id]);
Component Mapping (Class to Hooks)
| Class Lifecycle Method | Hook Equivalent |
| :--- | :--- |
| constructor | useState initialization |
| componentDidMount | useEffect(fn, []) |
| componentDidUpdate | useEffect(fn, [deps]) |
| componentWillUnmount | useEffect(() => { return fn }, []) |
| shouldComponentUpdate | React.memo(Component, areEqual) |
Modern Patterns
Custom Hooks
Extract reusable logic into standard JavaScript functions prefixed with use.
function useWindowSize() {
const [size, setSize] = useState([window.innerWidth, window.innerHeight]);
useEffect(() => {
const handleResize = () => setSize([window.innerWidth, window.innerHeight]);
window.addEventListener('resize', handleResize);
return () => window.removeEventListener('resize', handleResize);
}, []);
return size;
}
Component Composition
Avoid prop drilling by passing components as props (Children pattern).
function Card({ header, children, footer }) {
return (
<div className="card">
<div className="card-header">{header}</div>
<div className="card-body">{children}</div>
<div className="card-footer">{footer}</div>
</div>
);
}