Hooks Overview
Hooks Overview
Hooks were introduced in React 16.8. They allow you to use state and other React features without writing a class component. Before Hooks, functional components were strictly “stateless” or “dumb” components, and you had to use class components if you needed state or lifecycle methods.
Why were Hooks introduced?
- It was hard to reuse stateful logic between components: Before Hooks, patterns like Higher-Order Components (HOCs) and Render Props were used to share stateful logic. This often resulted in “wrapper hell” (a deeply nested tree of components). Hooks allow you to extract stateful logic into reusable functions (Custom Hooks) without changing your component hierarchy.
- Complex components became hard to understand: In class components, related logic is often split apart across different lifecycle methods (e.g., setting up a subscription in
componentDidMountand cleaning it up incomponentWillUnmount). Hooks allow you to group related code together based on what it does, rather than when it runs. - Classes confuse both people and machines: Understanding how the
thiskeyword works in JavaScript can be a major hurdle. Classes also minify poorly and make hot reloading flaky.
Built-in Hooks
React provides a few standard built-in hooks:
State Hooks
useState: Declares a state variable that you can update directly.useReducer: Declares a state variable with the update logic inside a reducer function (like Redux).
Context Hooks
useContext: Reads and subscribes to context from a component.
Ref Hooks
useRef: Declares a ref, which lets you hold any value in a mutable object that doesn’t trigger re-renders.
Effect Hooks
useEffect: Connects a component to an external system (like a network, DOM, or third-party library).useLayoutEffect: Fires before the browser repaints the screen.
Performance Hooks
useMemo: Caches the result of an expensive calculation.useCallback: Caches a function definition before passing it down.
Interview Questions
Q: Why were Hooks introduced in React 16.8?
A: Before Hooks, functional components were stateless and couldn’t access lifecycles; you had to use verbose Class components. Hooks were introduced to allow functional components to use state and side effects, and to solve the massive headache of reusing stateful logic (which previously required messy patterns like Higher-Order Components or Render Props).