What are Hooks?

🪝 Introduction to Hooks

React Hooks are special functions that allow functional components to use React features such as state, lifecycle, context, and more without writing class components. Hooks were introduced in React 16.8 to make components simpler, reusable, and easier to maintain.

Important

Hooks can only be called inside React function components or inside custom Hooks. They must always be called at the top level of the component.

🎯 Why Hooks?

Before Hooks, developers used class components whenever they needed state or lifecycle methods. Hooks brought these capabilities to functional components, making React code more concise and easier to understand.

  • Write components using plain JavaScript functions.
  • Reuse stateful logic through custom Hooks.
  • Reduce boilerplate compared to class components.
  • Improve readability and maintainability.

⚙️ How Hooks Work

Function Component
Calls a React Hook
React Stores Hook State
Updated UI is Rendered
Triggers Re-render When State Changes

📚 Common Built-in Hooks

HookPurposeCommon Use
useStateManage component stateForms, counters, toggles
useEffectPerform side effectsAPI calls, timers, subscriptions
useContextAccess shared contextTheme, authentication
useRefStore mutable values or access DOMFocus input, store previous values
useMemoMemoize expensive calculationsPerformance optimization
useCallbackMemoize functionsPrevent unnecessary re-renders

💡 Example: Using useState

The useState Hook lets a component remember values between renders.

Counter Component

import { useState } from "react";

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

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

Here, count stores the current value, while setCount updates it. Every update causes React to re-render the component with the latest state.

🔄 Example: Using useEffect

The useEffect Hook performs side effects after rendering, such as fetching data or updating the document title.

Document Title Example

import { useEffect } from "react";

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

  return <h1>Hello React</h1>;
}

Tip

The empty dependency array [] means the effect runs only once after the initial render.

📖 Rules of Hooks

  1. Always call Hooks at the top level of a component.
  2. Never call Hooks inside loops, conditions, or nested functions.
  3. Only call Hooks from React function components.
  4. Custom Hooks can call other Hooks.

🛠️ Custom Hooks

A Custom Hook is simply a JavaScript function whose name starts with use. It allows you to extract and reuse stateful logic across multiple components.

Custom Hook Example

import { useState } from "react";

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

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

  return { count, increment };
}

📊 Hooks at a Glance

Use useState whenever a component needs to remember changing values such as counters, form inputs, or toggles.

Use useEffect for tasks like fetching data, setting timers, subscribing to events, or synchronizing with external systems.

Use useMemo and useCallback to optimize rendering by avoiding unnecessary recalculations or function recreation.

🚀 Benefits of Hooks

  • Cleaner and shorter components.
  • Better code reuse through custom Hooks.
  • No need for class components in most cases.
  • Easier testing and maintenance.
  • Improved separation of concerns.

📅 Learning Path

📚 Official Resources

For more detailed information, refer to the official React documentation on React Hooks. It provides comprehensive explanations, examples, and best practices.

Summary

Hooks enable functional components to use React's powerful features such as state, effects, context, and performance optimizations. They simplify development, encourage reusable logic, and have become the standard way to write modern React applications.