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
Building Practical Custom Hooks (useLocalStorage, useDebounce)0%
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 IntermediateBuilding Practical Custom Hooks (useLocalStorage, useDebounce)
Composing Multiple Hooks and Custom Hook Testing

Building Practical Custom Hooks (useLocalStorage, useDebounce)

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

1. The Power of Utility Custom Hooks

In real-world web engineering, certain stateful patterns recur across virtually every application:

  • Persisting state changes to browser storage automatically.
  • Debouncing rapid input typing before dispatching expensive search queries.

Let's build two of the most widely used enterprise utility hooks from scratch.

2. Hook 1: useLocalStorage

A hook that behaves exactly like useState, but automatically synchronizes its value with browser localStorage:

1// src/hooks/useLocalStorage.js
2import { useState, useEffect } from 'react';
3 
4export function useLocalStorage(key, initialValue) {
5 // 1. Lazy initialization from localStorage
6 const [storedValue, setStoredValue] = useState(() => {
7 try {
8 const item = window.localStorage.getItem(key);
9 return item ? JSON.parse(item) : initialValue;
10 } catch (error) {
11 console.error(`Error reading localStorage key "${key}":`, error);
12 return initialValue;
13 }
14 });
15 
16 // 2. Synchronize to localStorage whenever storedValue changes
17 useEffect(() => {
18 try {
19 window.localStorage.setItem(key, JSON.stringify(storedValue));
20 } catch (error) {
21 console.error(`Error saving localStorage key "${key}":`, error);
22 }
23 }, [key, storedValue]);
24 
25 return [storedValue, setStoredValue];
26}

Consumer Usage:

1// Behaves just like useState, but survives page reloads!
2const [theme, setTheme] = useLocalStorage('msk_theme', 'dark');
3const [enrolledIds, setEnrolledIds] = useLocalStorage('msk_enrolled', []);

3. Hook 2: useDebounce

When a user types in a live search box, firing an API request on every keystroke floods your backend server with unnecessary network traffic.

Debouncing waits until the user has stopped typing for a specified delay (e.g. 500ms) before evaluating the value:

1// src/hooks/useDebounce.js
2import { useState, useEffect } from 'react';
3 
4export function useDebounce(value, delay = 500) {
5 const [debouncedValue, setDebouncedValue] = useState(value);
6 
7 useEffect(() => {
8 // Set a timer to update debouncedValue after the delay
9 const timer = setTimeout(() => {
10 setDebouncedValue(value);
11 }, delay);
12 
13 // Cleanup: cancel the timer if 'value' or 'delay' changes (user kept typing!)
14 return () => {
15 clearTimeout(timer);
16 };
17 }, [value, delay]);
18 
19 return debouncedValue;
20}

Consumer Usage in a Live Search Box:

1import React, { useState, useEffect } from 'react';
2import { useDebounce } from '../hooks/useDebounce';
3 
4export default function CourseSearch() {
5 const [searchTerm, setSearchTerm] = useState('');
6
7 // debouncedTerm updates ONLY after user stops typing for 500ms!
8 const debouncedTerm = useDebounce(searchTerm, 500);
9 
10 useEffect(() => {
11 if (debouncedTerm) {
12 console.log(`Executing API search query for: ${debouncedTerm}`);
13 // fetchSearchResults(debouncedTerm);
14 }
15 }, [debouncedTerm]); // Only fires API query on debounced change!
16 
17 return (
18 <div>
19 <input
20 type="text"
21 placeholder="Type to search curriculum..."
22 value={searchTerm}
23 onChange={(e) => setSearchTerm(e.target.value)}
24 />
25 <p>Instant Input: {searchTerm}</p>
26 <p>Debounced API Query: {debouncedTerm}</p>
27 </div>
28 );
29}

Interactive Quiz• Knowledge Check

Practice Quiz

Question 1
In the useDebounce hook, how is the pending timer cancelled if the user presses another key before the delay expires?
Question 2
What is the primary benefit of debouncing a search input before calling an API?
Question 3
Why does useLocalStorage use JSON.stringify and JSON.parse?
Question 4
Why is useLocalStorage's initial read wrapped in a try...catch block?
Question 5
What is returned by const [val, setVal] = useLocalStorage('key', 'default')?
Next Lesson

Composing Multiple Hooks and Custom Hook Testing

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

Related Lessons

Previous LessonNext Lesson
Extracting Reusable Business Logic into Custom HooksComposing Multiple Hooks and Custom Hook Testing

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