Hey DevLingo champs! Picture this: You've built an amazing React application. Your modal component is pixel-perfect, centered beautifully on the screen, ready to gather user input or display crucial information. But then, a user tries to scroll within the modal, accidentally flicks their mouse wheel or trackpad, and *whoosh* – the page *behind* the modal scrolls instead. Annoying, right?
This isn't just a minor UI glitch; it's a frustrating user experience that can cost you precious points in a technical interview for companies like TCS NQT, Infosys SP, or even Google India SDE-1. In the competitive Bangalore and Hyderabad startup scene, where salaries of ₹12LPA+ are on the table, attention to detail like this truly sets you apart.
Today, we're diving deep into a simple yet powerful solution: creating a custom **React `useScrollLock` hook** to **lock body scroll for modals**. This isn't just about fixing a bug; it's about showcasing a senior-level understanding of user experience and frontend architecture. Ready to level up your Placement Prep 2026?
The Annoying Problem: Background Scroll
When a modal is open, the user's focus should be entirely on its content. Allowing the underlying page to scroll distracts the user, can break the visual flow, and sometimes even makes the modal inaccessible if the background content shifts too much. It's a common oversight for freshers, but a quick fix for pros.
Why it's a Placement Red Flag
Interviewers, especially for SDE-1 roles at product companies, look for developers who think beyond just getting code to work. They want to see an understanding of:
- **User Experience (UX):** Do you prioritize the user's journey?
- **Browser API Knowledge:** Can you manipulate the DOM safely and effectively?
- **Custom Hooks Mastery:** Can you encapsulate reusable logic efficiently?
Solving the scroll lock problem with a custom hook demonstrates all three.
Introducing the `useScrollLock` Hook
Our goal is simple: when a modal opens, the `<body>` element should stop scrolling. When the modal closes, scrolling should resume normally. We'll achieve this by temporarily applying `overflow: hidden` to the `document.body`.
Step-by-Step: Building Your Custom Hook
Let's create a reusable custom hook. Open up your code editor and let's get coding!
```javascript import { useEffect, useState } from 'react';
const useScrollLock = (isLocked) => { useEffect(() => { // Get original body overflow and padding-right const originalOverflow = document.body.style.overflow; const originalPaddingRight = document.body.style.paddingRight;
if (isLocked) { // Calculate scrollbar width to prevent content jump const scrollbarWidth = window.innerWidth - document.documentElement.clientWidth;
document.body.style.overflow = 'hidden'; // Add padding-right to compensate for scrollbar removal document.body.style.paddingRight = `${scrollbarWidth}px`; } else { // Reset styles when not locked document.body.style.overflow = originalOverflow; document.body.style.paddingRight = originalPaddingRight; }
// Cleanup function: important for React's lifecycle return () => { document.body.style.overflow = originalOverflow; document.body.style.paddingRight = originalPaddingRight; }; }, [isLocked]); // Re-run effect when isLocked changes };
export default useScrollLock; ```
Decoding the Magic
- **`useEffect`:** This React hook is crucial for performing side effects (like directly manipulating the DOM). It runs after every render and cleans up before the component unmounts or before re-running if dependencies change.
- **`isLocked` Dependency:** The effect re-runs whenever `isLocked` (our boolean prop) changes. This means the scroll will lock when `isLocked` becomes `true` and unlock when it becomes `false`.
- **`overflow: hidden`:** This CSS property is the core of our solution. It prevents content from scrolling.
- **`padding-right` for Scrollbar Compensation:** When `overflow: hidden` is applied, the browser's scrollbar often disappears. This can cause a jarring content jump as the page width effectively increases. By calculating the scrollbar's width and applying `padding-right` equal to that width, we maintain visual stability. Smart, isn't it?
- **Cleanup Function (`return () => {...}`):** This is vital! It ensures that when our component unmounts or `isLocked` becomes `false`, the `document.body` styles are reset to their original values. Forgetting this is a common mistake and can lead to a permanently locked scroll on your entire application.
Integrating into Your Modal Component
Now, let's see how easy it is to use our new `useScrollLock` hook within a typical `Modal` component:
```javascript import React, { useState } from 'react'; import useScrollLock from './useScrollLock'; // Adjust path as needed
const MyModal = ({ isOpen, onClose, children }) => { useScrollLock(isOpen); // The magic line!
if (!isOpen) return null;
return ( <div className="modal-overlay" onClick={onClose}> <div className="modal-content" onClick={(e) => e.stopPropagation()}> <button className="close-button" onClick={onClose}>×</button> {children} </div> </div> ); };
// Example usage in App.js const App = () => { const [isModalOpen, setIsModalOpen] = useState(false);
return ( <div> <h1>My Awesome Page</h1> <button onClick={() => setIsModalOpen(true)}>Open Modal</button> <p>Lots of scrollable content here...</p> {/* ... more content ... */}
<MyModal isOpen={isModalOpen} onClose={() => setIsModalOpen(false)}> <h2>Welcome to DevLingo!</h2> <p>This is your modal content. The background won't scroll!</p> </MyModal> </div> ); };
export default App; ```
Notice that single line: `useScrollLock(isOpen);` – that's all it takes! Your modal will now open, lock the background scroll, and close gracefully, restoring normal scrolling.
Elevate Your Frontend Skills for High-Paying Placements
Mastering custom hooks like `useScrollLock` isn't just about fixing a minor UI bug; it's about adopting best practices that make your applications robust, user-friendly, and maintainable. Companies in Bangalore and Hyderabad, from established giants to cutting-edge startups, are actively seeking fresh talent with this level of detail and understanding.
By demonstrating your ability to solve real-world UX problems with elegant, reusable React patterns, you're not just preparing for an interview – you're building the foundation for a successful career earning those coveted ₹12LPA+ packages.
DevLingo challenges you to implement this hook in your next project! Share your solutions and doubts in the comments below. Keep learning, keep coding, and ace those placements!
FAQs About `useScrollLock` in Placement Interviews
Frequently Asked Questions
How does this appear in interviews like TCS NQT or Google India SDE-1?
Interviewers use this to gauge your problem-solving skills, understanding of React's `useEffect` and custom hooks, and attention to user experience. Expect questions like: 'How would you prevent background scrolling for a modal?' or 'Design a reusable hook for managing body scroll.' Demonstrating `useScrollLock` with proper cleanup and scrollbar compensation shows a mature approach, moving beyond basic component rendering to solving real-world UX challenges and handling browser-specific quirks.
What is a common mistake when implementing a scroll lock?
The most common mistake is forgetting to *clean up* the `document.body` styles. If you set `document.body.style.overflow = 'hidden';` but don't reset it when the modal closes or the component unmounts, the entire page will remain scroll-locked permanently. Another mistake is not accounting for the scrollbar width, which leads to a noticeable 'content jump' when the scrollbar disappears and reappears. Our `useEffect` cleanup function and `padding-right` compensation directly address these common pitfalls.
