← Back to Chapters

Introduction & Rules of React Hooks

⚛️ Introduction & Rules of React Hooks

? Quick Overview

React Hooks are special functions that allow functional components to use React features such as state, lifecycle methods, and context. Introduced in React 16.8, Hooks eliminate the need for class components while enabling cleaner and more reusable logic.

? Key Concepts

  • Hooks work only in functional components
  • They enable state and side effects without classes
  • Hook calls must follow strict ordering rules
  • Custom hooks help reuse logic across components

? Syntax / Theory

Hooks rely on the order in which they are called. React internally maps each Hook call to a stored state value based on call order, which is why breaking the rules leads to errors.

? Rule 1: Call Hooks at the Top Level

? View Code Example
// Hooks must be called at the top level of the component
function Example() {
const [count, setCount] = React.useState(0);
const [name, setName] = React.useState("");
}
? View Incorrect Example
// Calling Hooks inside conditions breaks Hook order
function Example() {
if (true) {
const [count, setCount] = React.useState(0);
}
}

? Rule 2: Call Hooks Only from React Functions

? View Code Example
// Hooks are valid inside React function components
function App() {
const [count, setCount] = React.useState(0);
return <p>Count: {count}</p>;
}
? View Incorrect Example
// Hooks cannot be used inside normal JavaScript functions
function increment() {
const [count, setCount] = React.useState(0);
}

? Live Example Explanation

When Hooks are called conditionally or outside React components, React cannot correctly associate state with Hook calls. This leads to runtime errors and unpredictable behavior.

? Common Built-in Hooks

  • useState – Manage local component state
  • useEffect – Handle side effects and lifecycle logic
  • useRef – Persist mutable values and DOM references
  • useContext – Consume context values
  • useReducer – Handle complex state logic

? Tips & Best Practices

  • Always place Hooks before any conditional logic
  • Prefix custom Hooks with use
  • Use ESLint rules to enforce Hook correctness
  • Split logic into multiple components if needed

? Try It Yourself

  1. Create a counter using useState
  2. Add useEffect to update the document title
  3. Move a Hook inside a condition and observe the error
  4. Build a custom Hook like useWindowSize