Common Hook Patterns

đŸĒ Introduction

As React applications grow, developers often encounter recurring ways of using Hooks. These Hook patterns help organize logic, improve code reuse, and make components easier to understand and maintain. Rather than solving every problem differently, these patterns provide consistent approaches to common development tasks.

Information

A Hook pattern is a common way of combining one or more Hooks to solve a specific problem, such as managing state, fetching data, or synchronizing with external systems.

📚 Most Common Hook Patterns

PatternPrimary Hook(s)Typical Use Case
Local StateuseStateForms, counters, toggles
Side EffectsuseEffectAPI requests, timers, subscriptions
Context SharinguseContextTheme, authentication, language
DOM AccessuseRefFocus inputs, store mutable values
Performance OptimizationuseMemo, useCallbackPrevent unnecessary calculations and renders
Reusable LogicCustom HooksShare functionality across components

đŸŽ¯ Pattern 1: Managing Local State

The most common pattern is storing and updating component-specific data using useState.

Managing State with useState

import { useState } from "react";

function Counter() {
  const [count, setCount] = useState(0);

  return (
    <button onClick={() => setCount(count + 1)}>
      {count}
    </button>
  );
}

Tip

Use useState when data belongs only to a single component.

🌐 Pattern 2: Performing Side Effects

Use useEffect whenever your component needs to interact with something outside of React, such as making API requests, updating the page title, or starting timers.

Using useEffect

import { useEffect } from "react";

function App() {
  useEffect(() => {
    document.title = "Dashboard";
  }, []);

  return <h1>Dashboard</h1>;
}

🎨 Pattern 3: Sharing Data with Context

Instead of passing props through many levels, useContext allows components to access shared values directly.

Using useContext

import { useContext } from "react";
import { ThemeContext } from "./ThemeContext";

function Header() {
  const theme = useContext(ThemeContext);

  return <h1>{theme}</h1>;
}

đŸŽ¯ Pattern 4: Accessing DOM Elements

The useRef Hook stores values that persist between renders and provides direct access to DOM elements when needed.

Using useRef

import { useRef } from "react";

function InputFocus() {
  const inputRef = useRef(null);

  return (
    <>
      <input ref={inputRef} />
      <button onClick={() => inputRef.current.focus()}>
        Focus
      </button>
    </>
  );
}

⚡ Pattern 5: Optimizing Performance

When calculations or functions are expensive to recreate, React provides useMemo and useCallback to optimize rendering performance.

Using useMemo

import { useMemo } from "react";

function Example({ numbers }) {
  const total = useMemo(() => {
    return numbers.reduce((sum, n) => sum + n, 0);
  }, [numbers]);

  return <h1>{total}</h1>;
}

â™ģī¸ Pattern 6: Creating Custom Hooks

When multiple components need the same stateful logic, extract it into a custom Hook. This improves reusability and keeps components focused on rendering.

Custom Hook Example

import { useState } from "react";

function useCounter() {
  const [count, setCount] = useState(0);

  const increment = () => setCount(count + 1);

  return { count, increment };
}

🔄 Pattern Selection

Application Requirement
Need Local Data?
Need Side Effects?
Need Shared Data?
Need DOM Access?
Need Better Performance?
Need Reusable Logic?
Use useState
Use useEffect
Use useContext
Use useRef
Use useMemo or useCallback
Create a Custom Hook

📊 Choosing the Right Pattern

Use useState when information belongs only to one component and changes over time.

Use useEffect for operations that occur after rendering, such as fetching data or interacting with browser APIs.

Use useContext or custom Hooks to share data and behavior between multiple components.

Use useMemo and useCallback only when performance optimization is actually needed.

✅ Best Practices

  • Keep each Hook focused on a single responsibility.
  • Create custom Hooks for reusable stateful logic.
  • Use useEffect only for side effects.
  • Avoid premature optimization with useMemo and useCallback.
  • Always follow the Rules of Hooks.

📚 Official Resource

To explore more Hook usage patterns and recommended practices, visit the official React documentation at React Documentation.

Summary

Common Hook patterns provide proven solutions for managing state, performing side effects, sharing data, interacting with the DOM, improving performance, and reusing logic. Understanding these patterns helps you write clean, maintainable, and scalable React applications.