Back to Cheatsheets
React

React Hooks

Built-in hooks and their use cases

State

3 items
CommandDescription
const [state, setState] = useState(initial)
Component state
setState(newValue)
Replace state
setState(prev => prev + 1)
Update based on previous

Effects

4 items
CommandDescription
useEffect(() => {})
Run on every render
useEffect(() => {}, [])
Run once on mount
useEffect(() => {}, [dep])
Run when dep changes
useEffect(() => { return () => {} })
Cleanup function

Context

3 items
CommandDescription
const ctx = createContext(default)
Create context
<Ctx.Provider value={val}>
Provide value
const val = useContext(Ctx)
Consume context

Refs

3 items
CommandDescription
const ref = useRef(initial)
Mutable ref object
ref.current
Access current value
<div ref={ref}>
Attach to DOM element

Performance

2 items
CommandDescription
useMemo(() => compute(), [deps])
Memoize expensive computation
useCallback(fn, [deps])
Memoize function reference

Reducer

2 items
CommandDescription
const [state, dispatch] = useReducer(reducer, initial)
Complex state logic
dispatch({ type: "ACTION" })
Send action to reducer