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
| Hook | Purpose |
|---|---|
| useState | Adds state to a functional component |
| useEffect | Runs side effects (requests, timers, subscriptions) |
| useContext | Lets you use context without Context.Consumer |
| useReducer | Manages state via a reducer (an alternative to useState) |
| useMemo | Caches computed values |
| useCallback | Caches functions |
| useRef | Creates a "reference" for storing a value between renders |
| useLayoutEffect | Similar to useEffect, but fires before paint |
| useImperativeHandle | Controls what's exposed to the parent via ref |
| useTransition, useDeferredValue | Manage deferred updates (React 18+) |
Rules of hooks
- Hooks can only be called at the top level of a component (not inside if, for, or nested functions).
- 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 readyPremium
A concise answer to help you respond confidently on this topic during an interview.