React Mastery / React Basics

Introduction To Hooks

πŸ” What are Hooks?

  • Hooks are special functions in React that let you use state and lifecycle features inside functional components.

  • Introduced in React 16.8.

  • They removed the need to write class components for most use cases.


❓ Why were Hooks introduced?

Before Hooks:

  • State and lifecycle methods worked only in class components.

  • Class components had problems:

    • Confusing this keyword

    • Manual binding of event handlers

    • Large and complex lifecycle methods

    • Hard to reuse logic between components

Hooks solved these issues by allowing:

  • State in functional components

  • Cleaner and shorter code

  • Better logic reuse

  • Easier learning and maintenance


βš™οΈ useState Hook

  • useState lets you add state to a functional component.

  • It returns:

    1. Current state value

    2. Function to update the state

Syntax:

const [state, setState] = useState(initialValue);

πŸ§ͺ Example using useState

🧠 How it works

  • useState(0) β†’ initializes state with 0

  • count β†’ current value

  • setCount β†’ updates state

  • Updating state re-renders the component


βš–οΈ Comparison: Hooks vs Class Components

Feature

Class Component

Hooks (Functional Component)

Component type

Class-based

Function-based

State handling

this.state

useState

State update

this.setState()

setStateFn()

this keyword

Required

❌ Not used

Event binding

Required

❌ Not needed

Lifecycle methods

componentDidMount, etc.

useEffect

Code length

More boilerplate

Cleaner & shorter

Logic reuse

Hard (HOCs, render props)

Easy (custom hooks)

Learning curve

Steeper

Easier

Modern React

❌ Less preferred

βœ… Recommended

πŸ“Œ Key Rules of Hooks

  • Use Hooks only in functional components

  • Call Hooks at the top level

  • Do not call Hooks inside loops or conditions