React Hooks Intro

Introduction to React Hooks

Hooks are functions that let you “hook into” React state and lifecycle features from function components. They were introduced in React 16.8 and completely changed how React code is written.

Why Hooks?

  • Reuse stateful logic between components without HOCs or render props
  • Split one component into smaller functions based on related pieces (not lifecycle methods)
  • Use state without classes โ€” function components become fully capable

The Two Rules of Hooks

WarningRule 1: Only call Hooks at the top level of a function component or custom hook. Never call them inside loops, conditions, or nested functions.

Rule 2: Only call Hooks from React function components or custom hooks โ€” not regular JavaScript functions.

// โœ… Correct
function MyComponent() {
  const [count, setCount] = useState(0); // top level โœ“
  useEffect(() => { /* ... */ }, []);    // top level โœ“
}

// โŒ Wrong โ€” Hook inside a condition
function BadComponent({ shouldFetch }) {
  if (shouldFetch) {
    useEffect(() => { fetch("/api/data"); }, []); // โŒ
  }
}

Built-in Hooks Overview

Hook Purpose
useState Local component state
useEffect Side effects (fetch, timers, subscriptions)
useContext Consume a Context value
useRef Mutable ref / direct DOM access
useReducer Complex state logic (like a mini Redux)
useMemo Memoize expensive computed values
useCallback Memoize function references
useId Generate stable unique IDs
useTransition Mark state updates as non-urgent

๐Ÿง  Test Yourself

Can you call a Hook inside an if statement?