Hooks and effects

What Hooks are

Use React functions that connect a component to state, context, refs, and synchronization features.

Hooks are functions that let a component use React features such as state, context, refs, and Effects.

import { useState } from 'react'

function Details() {
  const [open, setOpen] = useState(false)
  // ...
}

Built-in Hooks include useState, useEffect, useRef, and useContext. Custom Hook names also start with use.

A Hook call belongs to the component position currently rendering. React relies on the call order to match each Hook with its stored value. That is why Hooks must run in the same order on every render.

Think of Hooks as connections, not general utility functions:

  • useState connects the component to remembered state.
  • useContext reads a value from the nearest provider.
  • useRef keeps a mutable value or DOM reference between renders.
  • useEffect synchronizes with an external system after rendering.

A custom Hook packages repeated stateful behavior. It shares logic, not one state instance. Calling useOnlineStatus() in two components gives each call its own Hook state unless both subscribe to the same external source.

Do not add a Hook because a function starts with use. The name is a promise that the function follows Hook rules and may call other Hooks. A plain helper named useSomething that breaks those rules will fail in subtle ways.

You cannot call Hooks from a regular JavaScript function, only from React components and custom Hooks. That restriction is what makes the call-order model work.

Before Hooks, class components held state on this. Function components could not remember values between renders without lifting state up or using a wrapper. Hooks brought that memory into function components directly.

Open React DevTools and inspect a component with two useState calls. Change one value and notice how React preserves each Hook by position.

Lesson completed