React Hooks Cheatsheet
A comprehensive quick-reference for all built-in React hooks with code examples.
useState
Adds local state to a functional component. Returns the current state value and a setter function. Re-renders the component every time the state value changes.
import { useState } from 'react';
function Counter() {
const [count, setCount] = useState(0);
return (
<button onClick={() => setCount(c => c + 1)}>
Count: {count}
</button>
);
}
useEffect
Runs side effects after rendering. The dependency array controls when the effect re-runs. Return a cleanup function to cancel subscriptions or timers.
import { useEffect, useState } from 'react';
function DataFetcher({ userId }) {
const [user, setUser] = useState(null);
useEffect(() => {
let active = true;
fetch(`/api/users/${userId}`)
.then(r => r.json())
.then(data => { if (active) setUser(data); });
return () => { active = false; }; // cleanup
}, [userId]); // re-runs when userId changes
return <div>{user?.name}</div>;
}
useContext
Reads a value from the nearest matching Context provider. Avoids prop-drilling for global state like theme, auth, or locale.
const ThemeContext = React.createContext('light');
// Provider (parent)
<ThemeContext.Provider value="dark">
<App />
</ThemeContext.Provider>
// Consumer (any descendant)
function Button() {
const theme = useContext(ThemeContext); // 'dark'
return <button className={theme}>Click</button>;
}
useRef
Returns a mutable ref object whose .current property persists across renders without causing a re-render. Used to access DOM nodes or store any mutable value.
function FocusInput() {
const inputRef = useRef(null);
return (
<>
<input ref={inputRef} />
<button onClick={() => inputRef.current.focus()}>
Focus
</button>
</>
);
}
useMemo & useCallback
useMemo memoizes a computed value; useCallback memoizes a function reference. Both accept a dependency array and only recompute when dependencies change. Use to prevent unnecessary re-renders of child components.
const sorted = useMemo(
() => [...list].sort((a, b) => a - b),
[list] // only re-sorts when list changes
);
const handleClick = useCallback(() => {
doSomething(id);
}, [id]);
useReducer
An alternative to useState for managing complex state logic. Follows the Redux pattern: dispatch an action, a reducer function returns the next state.
const initialState = { count: 0 };
function reducer(state, action) {
switch (action.type) {
case 'increment': return { count: state.count + 1 };
case 'decrement': return { count: state.count - 1 };
default: throw new Error();
}
}
function Counter() {
const [state, dispatch] = useReducer(reducer, initialState);
return (
<>
<p>{state.count}</p>
<button onClick={() => dispatch({ type: 'increment' })}>+</button>
</>
);
}