State
Introduction
React hooks add state, effects, context and refs to function components. This reference targets React 19.
- Hooks reference (react.dev)
- Rules of hooks (react.dev)
useState
const [count, setCount] = useState(0)
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
The setter schedules a re-render; the new value appears on the next render.
See: useState
Updater functions
With an updater
setCount(c => c + 1)
setCount(c => c + 1) // both updates apply
setUser(u => ({ ...u, name }))
Without an updater
function Counter() {
const [count, setCount] = useState(0)
function handleClick() {
setCount(count + 1)
setCount(count + 1) // still 0 + 1
}
return <button onClick={handleClick}>{count}</button>
}
Pass a function when the next value depends on the previous one; React queues each updater and applies them in order. Without one, both calls read the same snapshot, so the counter adds one.
See: Updating state based on the previous state · State as a snapshot
Lazy initial state
const [items, setItems] = useState(() => loadItems())
The initializer runs once on mount; useState(loadItems()) calls it on every render and discards the result.
useReducer
function reducer(state, action) {
switch (action.type) {
case 'add':
return { todos: [...state.todos, action.todo] }
case 'clear':
return { todos: [] }
default:
throw new Error(`Unknown action: ${action.type}`)
}
}
const [state, dispatch] = useReducer(reducer, { todos: [] })
dispatch({ type: 'add', todo })
Prefer a reducer for related fields or updates that depend on several values. A third argument initialises lazily: useReducer(reducer, props, init).
See: useReducer
Effects
Effect anatomy
useEffect(() => {
const connection = createConnection(roomId)
connection.connect()
return () => connection.disconnect()
}, [roomId])
Setup runs after the commit; cleanup runs before the next setup and on unmount.
Dependency array
Once on mount
useEffect(() => {
logPageView()
}, [])
Every render
useEffect(() => {
logPageView()
})
On change
useEffect(() => {
logPageView(userId, pageId)
}, [userId, pageId])
[] runs once after mount; omitting the array re-runs after every commit; a dependency list re-runs when a value changes (Object.is). Keep values used in the effect in the list. StrictMode runs setup and cleanup twice in development.
See: Dependencies
Cleanup
useEffect(() => {
window.addEventListener('resize', onResize)
return () => {
window.removeEventListener('resize', onResize)
}
}, [onResize])
Every subscription, timer and listener needs a matching cleanup; React runs it before the next setup and on unmount.
Fetching data
useEffect(() => {
const controller = new AbortController()
fetch(`/api/users/${id}`, { signal: controller.signal })
.then(res => {
if (!res.ok) throw new Error(`HTTP ${res.status}`)
return res.json()
})
.then(setUser)
.catch(err => {
if (err.name !== 'AbortError') setError(err)
})
return () => controller.abort()
}, [id])
Abort drops stale responses when id changes; ignore the expected AbortError. Prefer a framework or query library for real apps.
When not to use an effect
Derive during render
const fullName = first + ' ' + last
const visible = items.filter(item => item.active)
Reset with a key
<Profile key={userId} user={user} />
Don't use effects for derived values, event responses or state resets.
Specialized effects
useLayoutEffect
const ref = useRef(null)
const [height, setHeight] = useState(0)
useLayoutEffect(() => {
const box = ref.current.getBoundingClientRect()
setHeight(box.height)
}, [])
Runs before paint, so measurements can update the DOM without a flicker. Reach for useEffect otherwise.
See: useLayoutEffect
useEffectEvent
const onConnected = useEffectEvent(() => {
showNotification(`Connected to ${roomId}`, theme)
})
useEffect(() => {
const connection = createConnection(roomId)
connection.on('connected', onConnected)
connection.connect()
return () => connection.disconnect()
}, [roomId])
Reads the latest props and state without re-running the effect. Call it from an effect or another Effect Event; added in 19.2.
See: useEffectEvent
useInsertionEffect
useInsertionEffect(() => {
const style = document.createElement('style')
style.textContent = css
document.head.appendChild(style)
return () => style.remove()
}, [css])
Runs before layout effects so CSS-in-JS libraries can inject styles; refs are not attached yet.
See: useInsertionEffect
Context
useContext
const ThemeContext = createContext('light')
function Toolbar() {
const theme = useContext(ThemeContext)
return <div className={theme}>Toolbar</div>
}
Reads the closest provider above the component; the default value applies when there is none.
See: useContext
Provider shorthand
<ThemeContext value="dark">
<Toolbar />
</ThemeContext>
React 19 renders the context object itself as the provider. <ThemeContext.Provider> still works.
See: createContext
use(context)
function Rule({ show }) {
if (!show) return null
const theme = use(ThemeContext)
return <hr className={theme} />
}
Unlike useContext, use(context) may be called conditionally and inside loops.
Custom context hook
const ThemeContext = createContext(null)
function useTheme() {
const theme = useContext(ThemeContext)
if (theme === null) throw new Error('No ThemeProvider')
return theme
}
A named hook with a guard fails loudly when the provider is missing.
See: Using context
Refs and DOM
useRef
function Search() {
const inputRef = useRef(null)
useEffect(() => {
inputRef.current.focus()
}, [])
return <input ref={inputRef} />
}
.current persists across renders without causing one; use it for DOM nodes and mutable values.
See: useRef
Mutable values
const clicks = useRef(0)
function onClick() {
clicks.current += 1 // no re-render
}
Don't read or write refs during render; keep the render output pure.
Ref callbacks
<div
ref={node => {
const observer = new ResizeObserver(onResize)
observer.observe(node)
return () => observer.disconnect()
}}
/>
A ref callback may return a cleanup that runs when the node detaches (v19).
See: Ref callbacks
useImperativeHandle
function Player({ ref }) {
const videoRef = useRef(null)
useImperativeHandle(ref, () => ({
play: () => videoRef.current.play()
}), [])
return <video ref={videoRef} />
}
Exposes a small imperative API instead of the DOM node; v19 also accepts ref as a prop.
See: useImperativeHandle
useId
function Field() {
const id = useId()
return (
<>
<label htmlFor={id}>Email</label>
<input id={id} type="email" />
</>
)
}
SSR-safe and unique; don't use it for list keys.
See: useId
Performance
useMemo
const visible = useMemo(
() => items.filter(item => item.active),
[items]
)
Caches a value between renders while the dependencies are equal; it is a performance hint, not a guarantee.
See: useMemo
useCallback
const onSelect = useCallback(
id => setSelected(id),
[]
)
useCallback(fn, deps) is useMemo(() => fn, deps); it matters for memoised children and effect dependencies. React Compiler 1.0 handles most cases.
See: useCallback
useTransition
const [isPending, startTransition] = useTransition()
function onChange(e) {
const value = e.target.value
setQuery(value)
startTransition(() => setResults(search(value)))
}
Marks updates as non-urgent so typing stays responsive; isPending lets you dim stale results.
See: useTransition
useDeferredValue
const deferredQuery = useDeferredValue(query)
const isStale = query !== deferredQuery
<List query={deferredQuery} dimmed={isStale} />
Renders the old value first and catches up in the background; an update inside a transition skips the deferred render.
See: useDeferredValue
useSyncExternalStore
function subscribe(callback) {
window.addEventListener('online', callback)
window.addEventListener('offline', callback)
return () => {
window.removeEventListener('online', callback)
window.removeEventListener('offline', callback)
}
}
function useOnlineStatus() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine,
() => true // server snapshot
)
}
Subscribes to an external store in concurrent rendering; the third argument is the server snapshot.
See: useSyncExternalStore
Actions and promises (v19)
useActionState
const [error, submitAction, isPending] = useActionState(
async (_prev, formData) => {
const name = formData.get('name')
if (!name) return 'Name is required'
const result = await updateName(name)
return result.error ?? null
},
null
)
return (
<form action={submitAction}>
<input name="name" />
<button disabled={isPending}>Save</button>
{error && <p>{error}</p>}
</form>
)
The action receives the previous state and the submitted FormData; React queues calls and exposes isPending.
See: useActionState
useFormStatus
import { useFormStatus } from 'react-dom'
function Submit() {
const { pending } = useFormStatus()
return <button disabled={pending}>Save</button>
}
function Form({ action }) {
return (
<form action={action}>
<Submit />
</form>
)
}
Must be called from a component rendered inside the <form>; it tracks the parent form, not one in the same component.
See: useFormStatus
useOptimistic
function NameForm() {
const [name, setName] = useState('Ana')
const [optimisticName, setOptimisticName] = useOptimistic(name)
async function action(formData) {
const next = formData.get('name')
setOptimisticName(next)
const saved = await saveName(next)
startTransition(() => setName(saved))
}
return (
<form action={action}>
<p>Your name is {optimisticName}</p>
<input name="name" defaultValue={name} />
</form>
)
}
Shows the next value while the action runs, then reconciles with the real state; call the setter inside an action or transition.
See: useOptimistic
use(promise)
function Comments({ commentsPromise }) {
const comments = use(commentsPromise)
return comments.map(c => <p key={c.id}>{c.text}</p>)
}
function Page({ commentsPromise }) {
return (
<Suspense fallback={<Spinner />}>
<Comments commentsPromise={commentsPromise} />
</Suspense>
)
}
Suspends until the promise resolves; cache the promise outside render so the same instance survives re-renders. use may be called conditionally.
See: use
Custom hooks
Extract a hook
function useDebounced(value, delay = 300) {
const [debounced, setDebounced] = useState(value)
useEffect(() => {
const id = setTimeout(() => setDebounced(value), delay)
return () => clearTimeout(id)
}, [value, delay])
return debounced
}
function Search({ input }) {
const query = useDebounced(input)
return <Results query={query} />
}
A custom hook is a function named use… that calls other hooks; every call gets its own state.
Share state with context
const CartContext = createContext(null)
function CartProvider({ children }) {
const [items, setItems] = useState([])
return (
<CartContext value={{ items, setItems }}>
{children}
</CartContext>
)
}
function useCart() {
return useContext(CartContext)
}
Wrap state and its setter in a context, then read it through a named hook.
Testing hooks
import { renderHook, act } from '@testing-library/react'
function useCounter() {
const [count, setCount] = useState(0)
return { count, increment: () => setCount(c => c + 1) }
}
const { result } = renderHook(() => useCounter())
act(() => result.current.increment())
expect(result.current.count).toBe(1)
renderHook mounts a wrapper component; wrap updates in act so React flushes them.
See: renderHook
useDebugValue
function useDiscount(user) {
const discount = user.tier === 'pro' ? 0.2 : 0
useDebugValue(discount, d => `${d * 100}% off`)
return discount
}
Labels the hook in React DevTools; the formatter runs only when the hook is inspected.
See: useDebugValue
Rules and tooling
Rules of hooks
| Rule | Why |
|---|---|
| Call hooks at the top level | Order identifies each hook's state |
| Call them from components or hooks | React needs a render context |
Name custom hooks use… | The linter recognises them |
| Never call them conditionally | Order must stay stable |
See: Rules of hooks
ESLint
eslint.config.js
import reactHooks from 'eslint-plugin-react-hooks'
export default [
reactHooks.configs.flat.recommended
]
Catches conditional hooks, missing effect dependencies and Effect Event misuse; add it alongside your JSX or TypeScript config.
Also see
- React cheatsheet — components, JSX and the wider API
- React v16 cheatsheet — class lifecycle equivalents
0 Comments for this cheatsheet. Write yours!