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.

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.

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

Take this course offline

Get every free book, course edition, and software download.

Get the download library →