React Hooks and Component Patterns

What You Will Learn

This guide explains how to build React applications with components, hooks, state, effects, and reusable patterns.

Prerequisites

  • JavaScript fundamentals
  • HTML and CSS basics
  • Basic npm usage

Concept Overview

React is a UI library based on components. Components receive data through props, manage local state with hooks, and render UI from state.

Important hooks:

  • useState
  • useEffect
  • useMemo
  • useCallback
  • useRef
  • Custom hooks

Step-by-Step Explanation

Start by creating small presentational components. Add props to make them reusable. Then introduce state for interactive behavior. Use effects only for synchronization with outside systems such as APIs, subscriptions, timers, and browser APIs.

When logic repeats, extract a custom hook. When UI repeats, extract a component. Keep server data, form state, and UI state separate where possible.

Code Example

TSX
import { useEffect, useState } from "react";

function useDebouncedValue<T>(value: T, delayMs = 300) {
  const [debouncedValue, setDebouncedValue] = useState(value);

  useEffect(() => {
    const timer = window.setTimeout(() => setDebouncedValue(value), delayMs);
    return () => window.clearTimeout(timer);
  }, [delayMs, value]);

  return debouncedValue;
}

Real-World Use Cases

  • Dashboards
  • Admin panels
  • Forms
  • Search interfaces
  • Learning platforms

Best Practices

  • Keep components focused.
  • Prefer derived values over duplicate state.
  • Avoid unnecessary effects.
  • Use stable keys when rendering lists.
  • Use custom hooks for reusable behavior.
  • Keep accessibility in mind for buttons, forms, and navigation.

Common Mistakes

  • Putting everything in one component
  • Using useEffect for simple calculations
  • Mutating state directly
  • Using array index as key for dynamic lists
  • Fetching data without loading and error states

Interview Questions

  • What is the difference between props and state?
  • When should you use useEffect?
  • What is a custom hook?
  • Why are keys important in lists?
  • How can you improve React performance?

Summary

React becomes manageable when components are small, state is intentional, and effects are used carefully. Hooks are powerful when they model behavior rather than hide complexity.