React hooks

On this page 8

React hooks are special functions, such as useState and useEffect, that let function components hold state, run side effects and access context in the React library. Introduced in React 16.8 in 2019, hooks replaced most uses of class components and lifecycle methods, and they now form the standard way to build interactive interfaces in Web applications that use React.

A hook connects a component to features that React manages outside the component function itself. Because each render calls the component function again, hooks give that function a stable memory between renders and a controlled place to synchronize with the outside world, such as the browser, a network API or a timer.

How React hooks store state between renders

React hooks work because React keeps a per-component list of hook slots and reads them in the order of the calls during each render. When a component calls useState first and useEffect second, React matches the first call to the first slot and the second call to the second slot on every later render.

This design explains the rules of hooks. Hooks must be called only at the top level of a function component or a custom hook, never inside conditions, loops or nested functions, and only from React functions, never from ordinary JavaScript helpers. Breaking the call order shifts the slots, so a component would read the wrong state. The official ESLint plugin for hooks detects most violations at build time.

A state update does not change the current variable. Calling the setter schedules a new render, and the new value appears only in the next call of the component function. Each render therefore sees a snapshot of props and state, which is the source of the familiar stale closure problem described later.

Built-in hooks and what each one does

React ships a small set of built-in hooks, each solving one category of problem. The table below lists the most used hooks and their typical purpose.

HookPurposeTypical use
useStateLocal state that triggers a re-renderForm inputs, toggles, counters
useReducerState updated through a reducer functionComplex state with many transitions
useEffectSynchronization after the browser paintsSubscriptions, data fetching, timers
useLayoutEffectSynchronization before the browser paintsMeasuring layout, avoiding flicker
useContextReads a value from the nearest providerTheme, locale, authenticated user
useRefMutable value that does not re-renderDOM nodes, timer IDs, previous values
useMemoCaches a computed valueExpensive derived data
useCallbackCaches a function identityCallbacks passed to memoized children
Core built-in React hooks

Newer versions added more specialized hooks. useId generates stable identifiers that match between server and client during hydration, useTransition and useDeferredValue mark updates as non-urgent for concurrent rendering, useSyncExternalStore connects to external stores safely, and React 19 introduced useActionState, useOptimistic and the use API for reading promises and context.

Custom hooks and reuse of stateful logic

A custom hook is an ordinary JavaScript function whose name starts with use and which calls other hooks. It is the main mechanism for sharing stateful logic between components without changing the component tree. Examples include useWindowSize, useDebounce or a useFetch hook that wraps loading, error and data states.

Custom hooks share logic, not state. Two components that call the same custom hook each receive their own independent state. To share the same data, developers still lift state to a common parent, use context or adopt an external store such as Redux. Before hooks, reuse relied on higher-order components and render props, which added wrapper layers and made component trees harder to read.

The following comparison shows how hooks differ from the class-based patterns they largely replaced.

AspectClass componentsFunction components with hooks
StateSingle this.state objectSeveral independent state variables
Side effectsSplit across lifecycle methodsGrouped by concern in effects
Logic reuseHigher-order components, render propsCustom hooks
The this keywordRequired, with binding issuesNot used
Error boundariesSupportedStill require a class component
Server ComponentsNot supportedSupported without client hooks
Class components compared with function components using hooks

The dependency array and effect timing

The dependency array tells React when to re-run an effect or recompute a memoized value. React compares each dependency with its previous value using Object.is, so a new object or function on every render counts as a change even when its contents are identical.

FormWhen the effect runsCommon use
No arrayAfter every renderRarely correct; debugging
Empty arrayAfter the first mount onlyOne-time subscriptions
Listed valuesWhen any listed value changesFetching by ID, syncing props
Dependency array forms for useEffect

An effect may return a cleanup function, which React calls before re-running the effect and when the component unmounts. Cleanup prevents memory leaks and race conditions, for example by removing event listeners or ignoring a network response that arrives after the user has navigated away. In development, Strict Mode mounts components twice on purpose to expose missing cleanup.

Common mistakes with React hooks

Most hook bugs come from misunderstanding render snapshots or treating effects as general event handlers. The table below links typical symptoms to their causes and fixes.

SymptomCauseFix
Infinite render loopEffect sets state it depends onRemove the dependency or derive the value
Stale values in callbacksClosure captured an old renderAdd dependencies or use functional updates
Effect runs too oftenObject or function recreated each renderMove it inside the effect or memoize it
Duplicate requests in developmentStrict Mode double mountingAdd cleanup or use a data library
Hook order errorHook called inside a conditionMove the call to the top level
Typical hook problems and their fixes

A further mistake is overusing useMemo and useCallback. Memoization has its own cost and helps only when it prevents expensive work or unnecessary renders of memoized children. The React Compiler, released for production use alongside React 19, can insert memoization automatically and reduces the need for manual tuning. Another frequent error is using an effect to compute derived data that can simply be calculated during rendering.

Hooks in modern React architectures

Hooks are a client-side feature. In frameworks such as Next.js that use React Server Components, server components cannot call useState or useEffect; any component that needs them must be marked with the "use client" directive. This split encourages developers to keep interactive state on the client and data loading on the server.

In server-side rendering, effects do not run on the server at all. They run only after hydration in the browser, which is why code that touches window or localStorage belongs inside an effect rather than in the component body.

In simple terms

A React component is a function that runs again every time the screen needs to update. On its own, such a function forgets everything between runs. Hooks give the function a memory and a safe way to talk to the outside world.

Think of a hook as a labeled drawer that React keeps for each component. useState stores a value in a drawer, and useEffect is a note saying what to do after the screen changes. React opens the drawers in the same order every time, which is why hooks must always be called in that fixed order.

A practical example

A team building a product search page for an online store needs a search box that queries an API as the user types. Sending a request on every keystroke would create dozens of requests per second and results arriving out of order.

The developers write a custom useDebouncedValue hook that combines useState and useEffect with a 300 millisecond timer, and a search effect that depends on the debounced text. The effect cleanup uses an AbortController to cancel outdated requests. The same custom hook is then reused in the address form and the admin filter panel.

The result is one request per pause in typing instead of one per character, no flickering of stale results, and shared logic that is tested once instead of copied into three components.