Skip to main content
Hooks are a powerful feature in Preact that let you use state and other features without writing a class component. Preact’s hooks implementation is fully compatible with React Hooks.

What are Hooks?

Hooks are functions that let you “hook into” Preact state and lifecycle features from function components. They make it easier to reuse stateful logic between components and organize your code.

Available Hooks

Preact provides all the standard hooks from the preact/hooks package:
  • useState - Manage local state
  • useEffect - Perform side effects
  • useReducer - Alternative to useState for complex state
  • useRef - Create a mutable ref object
  • useMemo - Memoize expensive computations
  • useCallback - Memoize callback functions
  • useContext - Access context values
  • useLayoutEffect - Run effects synchronously after DOM mutations
  • useImperativeHandle - Customize ref exposure
  • useDebugValue - Display custom hook labels in DevTools
  • useErrorBoundary - Catch errors in components
  • useId - Generate unique IDs for accessibility

useState

The useState hook lets you add state to function components. It returns an array with the current state value and a function to update it.

Functional Updates

When the new state depends on the previous state, pass a function to the setter:

useEffect

The useEffect hook lets you perform side effects in function components. Effects run after the browser paints, making them non-blocking.

useReducer

For complex state logic, useReducer is often preferable to useState. It’s built on top of useState internally.

Lazy Initialization

useReducer accepts an optional third argument for lazy initialization:

Rules of Hooks

Hooks have two important rules that must be followed:
Only call hooks at the top level of your function. Don’t call hooks inside loops, conditions, or nested functions.

Custom Hooks

Custom hooks let you extract component logic into reusable functions. They’re just functions that use other hooks.

Best Practices

Implementation Details

Preact’s hooks are implemented in hooks/src/index.js and integrate deeply with Preact’s rendering system. Key implementation details:
  • Hooks use an internal currentComponent variable to track which component is rendering
  • Each hook call increments a currentIndex counter to maintain hook state between renders
  • useState is implemented using useReducer internally
  • Effects are queued and flushed after painting using requestAnimationFrame
  • Hook state is stored in component.__hooks._list array
Reference: hooks/src/index.js:172-175

Next Steps

Context API

Learn how to share state across components using Context

Refs

Access DOM elements and persist values with refs