Mastering React: A Complete Tutorial Series for Beginners and Beyond

5.03K 0 0 0 0

Chapter 5: Hooks in Depth — From Basics to Custom Hooks

React Hooks revolutionized how we write components by bringing state and side effects to functional components. This chapter will help you master hooks from foundational to advanced use cases and even build your own custom hooks.


🧠 Why This Chapter Matters

Hooks let you write cleaner, more reusable, and testable components using functions instead of classes. They simplify logic and eliminate the need for lifecycle methods like componentDidMount.

In this chapter, you’ll learn:

  • What hooks are and how they work
  • How to manage state, effects, and context
  • How to optimize performance with memoization
  • How to build your own custom hooks

1. What Is a Hook?

Hooks are special functions that let you "hook into" React's features — like state, context, or lifecycle — without using classes.

🧩 Rules of Hooks:

  • Only call hooks at the top level
  • Only call hooks inside React function components or custom hooks

2. useState — Add State to Functional Components

import { useState } from 'react';

 

function Counter() {

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

 

  return (

    <>

      <h2>{count}</h2>

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

    </>

  );

}

Term

Meaning

useState(0)

Initializes state with value 0

count

Current state value

setCount

Function to update state


3. useEffect — Handle Side Effects

Used for:

  • Fetching data
  • Subscribing/unsubscribing
  • Updating the DOM manually

useEffect(() => {

  document.title = `Count: ${count}`;

}, [count]); // runs when `count` changes

Cleanup with return:

useEffect(() => {

  const timer = setInterval(() => console.log('Tick'), 1000);

  return () => clearInterval(timer); // cleanup

}, []);


4. useContext — Avoid Prop Drilling

const ThemeContext = React.createContext();

 

function App() {

  return (

    <ThemeContext.Provider value="dark">

      <Toolbar />

    </ThemeContext.Provider>

  );

}

 

function Toolbar() {

  const theme = useContext(ThemeContext);

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

}

useContext() gives you access to context values deep in the component tree.


5. useRef — Persistent Values & DOM Access

const inputRef = useRef();

 

function FocusInput() {

  return (

    <>

      <input ref={inputRef} />

      <button onClick={() => inputRef.current.focus()}>Focus</button>

    </>

  );

}

Also useful for storing values that don’t trigger re-renders, like a previous state.

const prevCount = useRef();

useEffect(() => {

  prevCount.current = count;

}, [count]);


6. useReducer — Advanced State Management

jsx

CopyEdit

const initialState = { count: 0 };

 

function reducer(state, action) {

  switch (action.type) {

    case "increment": return { count: state.count + 1 };

    case "decrement": return { count: state.count - 1 };

    default: return state;

  }

}

 

const [state, dispatch] = useReducer(reducer, initialState);

Great for complex state logic, especially forms or nested updates.


7. useCallback — Memoize Functions

const memoizedClick = useCallback(() => {

  console.log('Clicked');

}, []);

Prevents function recreation on every render — useful when passing functions to child components.


8. useMemo — Memoize Expensive Computations

const expensiveValue = useMemo(() => computeHeavyStuff(data), [data]);

Only recalculates when data changes.


9. Custom Hooks — Reuse Hook Logic

Custom hooks are just functions that start with use and contain other hooks.

function useLocalStorage(key, initialValue) {

  const [value, setValue] = useState(() => {

    const stored = localStorage.getItem(key);

    return stored ? JSON.parse(stored) : initialValue;

  });

 

  useEffect(() => {

    localStorage.setItem(key, JSON.stringify(value));

  }, [key, value]);

 

  return [value, setValue];

}

Clean, reusable, and testable logic across components.


🧪 Example: useForm Custom Hook

function useForm(initial = {}) {

  const [form, setForm] = useState(initial);

 

  const handleChange = (e) => {

    setForm({ ...form, [e.target.name]: e.target.value });

  };

 

  return [form, handleChange];

}

 

// Usage

const [data, handleInput] = useForm({ name: '', email: '' });


Summary Table


Hook

Purpose

Best Use Case

useState

Adds state to function components

Counter, toggles, inputs

useEffect

Runs after render (side effects)

API calls, timers, DOM updates

useContext

Reads values from context

Global state, theming, auth

useRef

Persistent value without re-render

Accessing DOM, storing previous values

useReducer

Complex state management

Form, shopping cart, game logic

useCallback

Memoize functions to avoid re-renders

Stable event handlers

useMemo

Memoize expensive calculations

Sorting, filtering, derived values

Custom Hook

Reusable logic built from hooks

Forms, fetchers, animations

Back

FAQs


1. What is React and why is it popular?

React is a JavaScript library for building user interfaces. It’s fast, modular, and backed by Facebook, making it popular for modern frontend development.

2. Do I need to know JavaScript before learning React?

Yes. A solid understanding of ES6+ JavaScript (like arrow functions, destructuring, and promises) is essential.

3. What’s the difference between a component and a hook?

A component is a UI building block; a hook is a function that lets you “hook into” React features inside functional components.

4. Is React a framework or a library?

Technically a library, but it’s often considered a framework because it’s used to build entire applications.

5. What are the most important hooks in React?

useState, useEffect, useContext, useRef, and useMemo are most commonly used.

6. Can I use React without Node.js?

Yes — but Node.js is typically used for tooling, package management, and running development servers.

7. Is Redux still relevant with React hooks and Context API?

Yes for large, complex apps. But for small to medium apps, Context API and hooks are often enough.

8. How long does it take to learn React?

Basic concepts can be learned in a few weeks; becoming proficient depends on how often you build projects and practice.

9. Is React better than Angular or Vue?

It depends on your project needs, but React is widely adopted and has a huge community, making it a strong choice.

10. How do I deploy a React app?

You can deploy to services like Vercel, Netlify, or GitHub Pages with just a few clicks — or use traditional hosting for more control.