April 8, 2024

What are hooks in React

In React, Hooks are special functions that let you use state and other React features in function components — things you could previously only do in class components.


✅ Why Hooks?

Before hooks, if you wanted to use state or lifecycle methods, you had to write class components. Hooks allow you to:

  • Use state, side effects, context, and more in function components
  • Share logic easily across components
  • Make components simpler and cleaner

🧰 Commonly Used React Hooks

HookPurpose
useState()Adds local state to a function component
useEffect()Handles side effects (e.g., data fetching, subscriptions)
useContext()Accesses React context
useRef()Stores a mutable reference that doesn’t trigger re-render
useMemo()Caches expensive calculations
useCallback()Caches function definitions
useReducer()An alternative to useState for complex state logic
useLayoutEffect()Like useEffect, but runs synchronously after render
useImperativeHandle()Customize the instance value exposed to parent with ref

🔧 Examples

1. useState

const [count, setCount] = useState(0);

2. useEffect

useEffect(() => {
  console.log("Component mounted or updated");
}, [count]); // Re-run effect when `count` changes

3. useRef

const inputRef = useRef();
<input ref={inputRef} />

🧠 Rules of Hooks

  1. ✅ Call hooks at the top level of your function (not inside if/for/loops)
  2. ✅ Only call hooks in React function components or custom hooks

📦 Custom Hooks

You can write your own hooks to reuse logic across components:

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);

  useEffect(() => {
    const handleResize = () => setWidth(window.innerWidth);
    window.addEventListener("resize", handleResize);
    return () => window.removeEventListener("resize", handleResize);
  }, []);

  return width;
}

🧾 Summary

HookClass Equivalent
useStatethis.state / setState()
useEffectcomponentDidMount, componentDidUpdate, componentWillUnmount
useRefcreateRef
useContextContext.Consumer