Chapter 12: React Hooks Deep Dive

These are the most powerful advanced hooks that every serious React developer uses daily. We’ll go through each one slowly, clearly, with real-world examples you can copy-paste right now — like I’m sitting next to you in Mumbai explaining it live on the screen.

Let’s dive in! 🚀

1. useRef – For Mutable Values & DOM Access

useRef creates a mutable reference that persists across renders but does NOT cause re-renders when it changes.

Two main uses:

  1. Accessing DOM elements (focus input, scroll, measure size…)
  2. Storing mutable values that survive re-renders (previous state, timers, intervals…)

Syntax:

tsx

Example 1: Focusing an Input on Button Click

tsx

Example 2: Storing Previous State (Common Pattern)

tsx

Key takeaway: useRef value doesn’t trigger re-render when changed — perfect for values you want to remember but not display.

2. useReducer – For Complex State Logic

useReducer is like useState on steroids — great when you have complex state updates or multiple related values.

Syntax:

tsx
  • reducer: pure function (state, action) => newState
  • dispatch: function to send actions

Example: Todo App with useReducer

tsx

When to choose useReducer over useState:

  • State is an object/array with multiple fields
  • Updates depend on previous state in complex ways
  • You want action-based logic (like Redux)

3. useContext – Sharing State Without Prop Drilling

useContext lets you share state deeply in the component tree without passing props through every level.

Steps:

  1. Create Context
  2. Provide value at top level
  3. Consume with useContext

Example: Theme Switcher

tsx

4. useMemo & useCallback – Performance Optimization

Both memoize values/functions so they don’t get recreated on every render.

Hook What it memoizes When to use
useMemo Value (calculation) Expensive calculations (filtering big array, complex math)
useCallback Function When passing callbacks to child components (prevents unnecessary re-renders)

Example: useMemo for Expensive List Filtering

tsx

Example: useCallback to Prevent Child Re-renders

tsx

5. Custom Hooks – Reusing Logic

Custom hooks are functions that start with use and can call other hooks.

Example: useLocalStorage (Super Useful!)

tsx

Summary – Chapter 12 Key Takeaways

  • useRef → DOM access + mutable values that don’t cause re-renders
  • useReducer → complex state logic, action-based updates
  • useContext → share state deeply without prop drilling
  • useMemo → memoize expensive calculations
  • useCallback → memoize functions (especially callbacks to children)
  • Custom hooks → extract and reuse stateful logic

Mini Homework

  1. Create useWindowSize custom hook that returns { width, height } and updates on resize
  2. Use it in a component to show different content on mobile vs desktop

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *