Skip to main content

What is a hook in React?

A hook in React is a special function that lets you "plug in" React's internal capabilities (such as state, lifecycle, context, etc.) inside functional components, without the need to use classes.


In simple terms

Hooks give functional components a "brain": they let them remember state, react to changes, run side effects, and interact with context.


Example: useState

The useState hook adds state to a functional component.

javascript
import { useState } from "react"; function Counter() { const [count, setCount] = useState(0); // the useState hook return ( <div> <p>Count: {count}</p> <button onClick={() => setCount(count + 1)}>Increase</button> </div> ); }

Here, useState(0):

  • creates the internal state count,
  • returns a pair [value, update function].

Example: useEffect

The useEffect hook is used for side effects, for example, API requests, working with the DOM, or subscriptions.

javascript
import { useState, useEffect } from "react"; function User() { const [user, setUser] = useState(null); useEffect(() => { fetch("/api/user") .then(res => res.json()) .then(setUser); }, []); // empty array -> runs once on mount return <div>{user ? user.name : "Loading..."}</div>; }

Main built-in React hooks

HookPurpose
useStateAdds state to a functional component
useEffectRuns side effects (requests, timers, subscriptions)
useContextLets you use context without Context.Consumer
useReducerManages state via a reducer (an alternative to useState)
useMemoCaches computed values
useCallbackCaches functions
useRefCreates a "reference" for storing a value between renders
useLayoutEffectSimilar to useEffect, but fires before paint
useImperativeHandleControls what's exposed to the parent via ref
useTransition, useDeferredValueManage deferred updates (React 18+)

Rules of hooks

  1. Hooks can only be called at the top level of a component (not inside if, for, or nested functions).
  2. Hooks can only be called inside functional components or custom hooks.

Why did React introduce hooks?

Before hooks, state and effect logic was available only in class components. Hooks made it possible to:

  • write less code,
  • reuse logic through custom hooks,
  • get rid of the confusion around this.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.