MSK Institute LogoMSK.Institute
HomeCourses
Book Free Demo➔Sign In
Free Demo➔
MSK Institute LogoMSK.Institute

Leading computer training academy in Shikohabad for software engineering, Python, web development, and digital literacy.

ISO 9001:2015 Certified Center
Follow & Connect
4.9

Programs & Admissions

  • All CoursesCatalog
  • Learning PathsRoadmaps
  • Student ProjectsShowcase
  • Live Classes & ScheduleLive
  • Upcoming Batches
  • Campuses & LocationsHub
  • Verify Certificates
  • Book Free Demo Class

Resources & Tools

  • Free Online Mock TestsAll Tests
  • NIELIT CCC Mock TestFree
  • Course & Career FinderQuiz
  • Study Material Hub
  • All MSK ToolsHub
  • Keyboard ShortcutsNew
  • TypeQuest Speed LabTyping
  • MSK Code PlaygroundCode
  • Interactive Tutorials
  • Quick Cheatsheets

Institute & Contact

  • About MSK Institute
  • Careers & InternshipsHiring
  • Publications & Blogs
  • Gali No. 3, Near Gyan Jyoti Public School,
    Adarsh Nagar, Shikohabad, Uttar Pradesh 283135
  • +91 83930 42166
  • mskshikohabad@gmail.com
  • Hours:Mon – Sat: 8:00 AM – 7:00 PM | Sun: 10:00 AM – 2:00 PM
  • 4.9 ★(38 Google Reviews)
© 2026 MSK Institute. All rights reserved.•Privacy Policy•Terms of Service•Disclaimer•Contact Us

Shikohabad's Leading Computer & Coding Academy

Home
Courses
Live
Material
Extracting Reusable Business Logic into Custom Hooks0%
Study Materials
React.js for IntermediateProgress 0%
1.1Component Reusability and Polymorphic Components1.2Render Props Pattern in Modern React1.3Higher-Order Components vs Modern Hooks1.4Compound Components Pattern Explained
9.1Extracting Reusable Business Logic into Custom Hooks9.2Building Practical Custom Hooks (useLocalStorage, useDebounce)9.3Composing Multiple Hooks and Custom Hook Testing
HomeTutorialsReact.js for IntermediateExtracting Reusable Business Logic into Custom Hooks
Building Practical Custom Hooks (useLocalStorage, useDebounce)

Extracting Reusable Business Logic into Custom Hooks

Beginner12 min read•Updated: 2026-11-18•By Er. Sumit Kumar (MSK Institute)
Study MaterialsCheatsheet

1. What Are Custom Hooks?

In early React, sharing stateful logic between components required complex patterns like Higher-Order Components (HOCs) or Render Props.

A Custom Hook is simply a JavaScript function whose name starts with use and that can call other React hooks (useState, useEffect, useRef, etc.).

Custom hooks allow you to extract component logic into reusable functions:

  • Components focus purely on presentation and user interface.
  • Custom hooks encapsulate state, network requests, and business rules.
1Component:
2[Focus on JSX, Layout, CSS, and UI Controls]
3 │
4 ▼ calls custom hook: const { isOnline } = useOnlineStatus();
5Custom Hook (useOnlineStatus):
6[Encapsulates useState, useEffect, window event listeners]

2. The Naming Convention Rule

A custom hook must start with the lowercase word use (e.g., useAuth, useWindowSize, useFetch):

  • React's ESLint plugin uses this naming prefix to automatically enforce the Rules of Hooks inside your custom function (ensuring hooks aren't called conditionally or in loops).
  • If you omit the use prefix, React will treat it as a standard function and will not warn you when hook violations occur.

3. Extracting a Window Dimensions Hook

Consider how multiple components (carousels, responsive charts, navigation drawers) need to know the browser's viewport width:

Without Custom Hook:

Every component duplicates 15 lines of useState, useEffect, and resize event listeners.

With Custom Hook (useWindowSize):

1// src/hooks/useWindowSize.js
2import { useState, useEffect } from 'react';
3 
4export function useWindowSize() {
5 const [windowSize, setWindowSize] = useState({
6 width: typeof window !== 'undefined' ? window.innerWidth : 1200,
7 height: typeof window !== 'undefined' ? window.innerHeight : 800
8 });
9 
10 useEffect(() => {
11 const handleResize = () => {
12 setWindowSize({
13 width: window.innerWidth,
14 height: window.innerHeight
15 });
16 };
17 
18 window.addEventListener('resize', handleResize);
19 return () => window.removeEventListener('resize', handleResize);
20 }, []);
21 
22 return windowSize;
23}

Clean Consumer Component:

1// src/components/ResponsiveDashboard.jsx
2import React from 'react';
3import { useWindowSize } from '../hooks/useWindowSize';
4 
5export default function ResponsiveDashboard() {
6 const { width } = useWindowSize(); // 1 clean line of code!
7 
8 const isMobile = width < 768;
9 
10 return (
11 <div>
12 {isMobile ? <MobileNavigation /> : <DesktopSidebar />}
13 </div>
14 );
15}

4. Do Components Using the Same Custom Hook Share State?

*No! Custom Hooks share stateful logic, NOT state itself!*

Each call to a custom hook creates a completely independent container of state. If Component A and Component B both call useWindowSize(), each component has its own private windowSize state in React's Fiber tree. (If you want components to share the exact same state instance, combine the custom hook with React Context).


Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
What prefix must all custom React hooks begin with?
Question 2
Do two components that call the same custom hook share the exact same state values?
Question 3
What can a custom hook return?
Question 4
Which of the following is a primary architectural benefit of extracting custom hooks?
Question 5
Can a custom hook invoke other built-in React hooks like useState and useEffect?
Next Lesson

Building Practical Custom Hooks (useLocalStorage, useDebounce)

Continue learning with hands-on practice, examples, and exercises in the upcoming topic.

Related Lessons

Previous LessonNext Lesson
The useMemo Hook and Expensive ComputationsBuilding Practical Custom Hooks (useLocalStorage, useDebounce)

Practice Quiz

Test your understanding of this lesson with 5 questions. Each question has one correct answer.

Mentor-Led Practical Training

Master React.js for Intermediate with Hands-On Projects

Practice in live mentor-led sessions with real projects, mock tests, and verifiable certification at MSK Institute.

View Full CourseBook Free Demo
PreviousNext
PreviousPrevNext