What do hooks do?
What hooks actually do
1. useState - stores state
Lets a component "remember" values between renders.
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0); // state
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}React "remembers" the value of count for each instance of the component and re-renders it when it changes.
2. useEffect - runs side effects
Handles actions that are not directly tied to rendering:
- API requests,
- subscriptions,
- timers,
- working with the DOM.
useEffect(() => {
console.log("Component mounted");
return () => console.log("Component removed");
}, []);useEffect with an empty array runs once on mount and returns a "cleanup" that runs on unmount.
3. useContext - connects to context
Lets you get data from context without props.
const ThemeContext = createContext("light");
function App() {
return (
<ThemeContext.Provider value="dark">
<Button />
</ThemeContext.Provider>
);
}
function Button() {
const theme = useContext(ThemeContext);
return <button className={theme}>Theme: {theme}</button>;
}Instead of "threading" props through many levels, you can get the needed value directly.
4. useRef - stores a reference to the DOM or a value between renders
function InputFocus() {
const inputRef = useRef();
useEffect(() => {
inputRef.current.focus(); // focus on mount
}, []);
return <input ref={inputRef} />;
}useRef does not trigger a re-render when .current changes.
5. useMemo - caches computations
Improves performance by not recalculating expensive values on every render.
const sortedUsers = useMemo(() => sortUsers(users), [users]);6. useCallback - caches functions
Helps avoid recreating handlers on every render.
const handleClick = useCallback(() => {
console.log("clicked");
}, []);7. useReducer - manages state through a reducer
An analog of Redux inside a component.
function reducer(state, action) {
if (action.type === "inc") return { count: state.count + 1 };
return state;
}
const [state, dispatch] = useReducer(reducer, { count: 0 });8. useLayoutEffect - a synchronous effect
Similar to useEffect, but runs before painting, synchronously.
Used when you need to measure the DOM before it appears on screen.
9. useTransition, useDeferredValue - managing deferred updates
Needed for UI optimization when rendering large lists, for example in React 18.
Summary
| Hook | What it does |
|---|---|
useState | Stores state |
useEffect | Runs side effects |
useContext | Gets data from context |
useRef | Stores a reference or an unchanging value |
useMemo | Caches computations |
useCallback | Caches functions |
useReducer | Manages state through a reducer |
useLayoutEffect | An effect that runs before rendering |
useTransition, useDeferredValue | Make updates non-blocking |
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.