Lesson 28/100

Tutorials React.js Tutorial

useCallback — Complete Guide

useCallback — Complete Guide: free step-by-step lesson with examples, common mistakes, and interview tips — part of React.js Tutorial on Toolliyo Academy.

On this page

React.js Tutorial · Lesson 28 of 100

Custom Hooks

Beginner ✓IntermediateAdvancedProfessional

Intermediate · 2 — Building apps · ~14 min read · Module 3: Hooks & Component Design

Introduction

You know the basics now. Here we use Custom Hooks in real app situations — forms, pages, and data. Still plain language, just a bit more depth. A custom hook is a function starting with use that calls other hooks. It lets you reuse stateful logic across components. If two components both fetch user data or track window size, extract that logic into useUser or useWindowWidth.

Hooks look strange at first. Every React developer felt that way. Use the same pattern from this lesson again and again until it feels normal.

When will you use this?

Reach for hooks whenever the screen must react to user input, time, or data from an API.

  • Hooks power live search, dark mode toggles, and fetching data when a page opens.
  • Almost every React job posting mentions hooks — this is core daily work.

Real-world: useAuth shared across app

Toolliyo has login on web and instructor portal. useAuth encapsulates token storage, refresh, and logout — imported in Navbar, Profile, and ProtectedRoute.

Production-style code

function useAuth() {
  const [user, setUser] = useState(() => JSON.parse(localStorage.getItem('user')));
  const [loading, setLoading] = useState(!user);

  useEffect(() => {
    if (user) return;
    fetch('/api/me', { credentials: 'include' })
      .then(r => r.ok ? r.json() : null)
      .then(u => { setUser(u); setLoading(false); });
  }, [user]);

  const logout = () => {
    localStorage.removeItem('user');
    setUser(null);
  };

  return { user, loading, logout };
}

What happens in production: Five pages share identical auth logic — fix token refresh once in the hook, all screens benefit.

Lesson example (start here)

Copy this smaller example first. Once it works, compare it with the real-world code above.

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  useEffect(() => {
    const onResize = () => setWidth(window.innerWidth);
    window.addEventListener('resize', onResize);
    return () => window.removeEventListener('resize', onResize);
  }, []);
  return width;
}

function Layout() {
  const width = useWindowWidth();
  return <p>Width: {width}px</p>;
}

Line-by-line walkthrough

CodeWhat it means
function useWindowWidth() {Defines a function — often a component or event handler.
const [width, setWidth] = useState(window.innerWidth);Creates state: a value that can change, plus a function to update it.
useEffect(() => {Runs side effects — fetch data, timers, or subscriptions — after the screen updates.
const onResize = () => setWidth(window.innerWidth);Defines a function — often a component or event handler.
window.addEventListener('resize', onResize);Part of the Custom Hooks example — read it together with the lines before and after.
return () => window.removeEventListener('resize', onResize);Returns JSX — the HTML-like UI this component displays.
}, []);Closes a block started by { or ( above.
return width;Sends UI or a value back to whoever called this function.
}Closes a block started by { or ( above.
function Layout() {Defines a function — often a component or event handler.
const width = useWindowWidth();Part of the Custom Hooks example — read it together with the lines before and after.
return <p>Width: {width}px</p>;Sends UI or a value back to whoever called this function.
}Closes a block started by { or ( above.

How it works (big picture)

  • useWindowWidth encapsulates subscribe/cleanup.
  • Layout stays simple.
  • Custom hooks must follow Rules of Hooks.

Do this on your computer

  1. Find duplicated useState + useEffect in two components.
  2. Move to hooks/useSomething.js.
  3. Call useSomething() from both components.
  4. Read the real-world section and name which part of the app uses this topic.
  5. Run the example locally and confirm the same behavior in the browser.
  6. Change one value in the example (text, initial state, or URL) and predict what will happen before you save.

Experiments — try changing this

  • Change text or labels in the example and save — watch the browser update.
  • Break the code on purpose (remove a bracket), read the error message, then fix it.
  • Change the initial state value and see the starting UI change.
  • Open React DevTools (browser extension) while running Custom Hooks and inspect component props/state.

Remember

Custom hooks reuse logic, not JSX. Name with use prefix. Compose built-in hooks inside.

Common questions

Can custom hooks return JSX?

They can, but usually return data and handlers; keep UI in components.

How long should I spend on Custom Hooks?

Until you can explain it in your own words and run the example without looking at the answer. Beginners often need 30–60 minutes per new hook or routing topic; setup lessons may take one afternoon.

What if I get stuck on Custom Hooks?

Re-read the line-by-line walkthrough, check the browser console for red errors, and compare your code character-by-character with the example. Search the exact error text — someone else had it too.

Where is Custom Hooks used in real jobs?

See the real-world section above — the same pattern appears in LMS, banking, e-commerce, and SaaS products. Interviewers ask you to explain it using one concrete example from your project or this lesson.

Questions on this lesson 0

Sign in to ask a question or upvote helpful answers.

No questions yet — be the first to ask!

React.js Tutorial
Course syllabus

React.js Tutorial

Module 1: React Basics & Setup
Module 2: Props, Events & Lists
Module 3: Forms & Hooks
Module 4: Routing & Data
Module 5: State & Authentication
Module 6: Architecture & React 19
Module 7: Performance
Module 8: Full-Stack & Real-Time
Module 9: Testing & Deployment
Module 10: ShopCart Projects
Toolliyo Assistant
Ask about tutorials, ebooks, training, pricing, mentor services, and support. I use public site content only—not admin or internal tools.

care@toolliyo.com

Need callback? Share your details