⚛️ Top 150 React Interview Questions – 121/150 📌 Topic: Mocking API Calls ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Mocking API calls means creating a fake server response during testing instead of calling a real backend. Instead of waiting for a live API, you simulate what the server would return. 👉 Your test behaves as if the API responded — but no real network request is made. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY use it? ⚡ Speed Mocked tests run instantly. No network delay. 🔒 Stability Tests won’t fail because the backend is down. 🎯 Full Control You can simulate: 200 Success 404 Not Found 500 Server Error Empty response [] Without changing real backend code. 💰 Cost Efficient No need to hit production databases during CI/CD runs. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW to do it? Industry standard tools: Jest MSW (Mock Service Worker) ✅ Basic Jest Mock Example // 1. Fake API Response const mockResponse = { id: 1, name: "John Doe" }; // 2. Mock fetch test('renders user name', async () => { global.fetch = jest.fn(() => Promise.resolve({ json: () => Promise.resolve(mockResponse), }) ); render(<UserComponent />); expect(await screen.findByText('John Doe')).toBeInTheDocument(); }); 👉 The component thinks it received real data. But the server was never contacted. 🔥 Pro Tip (Production-Ready Approach) Use MSW for realistic API interception instead of manually mocking fetch. It intercepts requests at the network level — cleaner and more scalable. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE to use it? 🧪 Integration Tests Components that fetch data inside useEffect. 🚀 CI/CD Pipelines Ensures automated tests run without real backend dependency. ⚠️ Edge Cases Test: Empty state UI Error UI Loading UI Without breaking real APIs. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY (Easy to Remember) Think of a Movie Set 🎬 If a scene needs a “Diamond,” the director doesn’t use a real one. They use a Glass Prop (Mock). It looks real on camera (the test), costs nothing, and avoids risking the real expensive diamond (Production Database). Mocks protect your real system while keeping your tests fast and reliable. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #Testing #Mocking #Jest #MSW #FrontendDevelopment #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
Mocking API Calls in React with Jest and MSW
More Relevant Posts
-
⚛️ Top 150 React Interview Questions – 139/150 📌 Topic: 💉 Dependency Injection ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Dependency Injection (DI) is a design pattern where a component receives its dependencies (services, utilities, data sources) from the outside instead of creating them internally. Instead of this ❌ Component creates its own API client We do this ✅ Component receives the API client from its parent Component focuses on what to do, not how tools are built. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY use Dependency Injection? 🔗 Decoupling Component is not tightly bound to a specific implementation. 🧪 Testability You can inject mock services instead of real APIs during testing. ♻️ Reusability Same component can work with different services. 🔄 Flexibility Swap behavior without rewriting the component. Cleaner architecture. Less chaos. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW to implement in React? In React, DI is done using: • Props (simple injection) • Context API (global injection) ✅ 1. Service (Dependency) const api = { fetch: () => ["Apple", "Orange"] }; ✅ 2. Component (Dependency Injected via Props) const List = ({ service }) => ( <ul> {service.fetch().map(item => ( <li key={item}>{item}</li> ))} </ul> ); ✅ 3. Injector (Parent Provides Dependency) const App = () => <List service={api} />; Component doesn’t know where data came from. It only knows how to render it. That’s DI. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE to use it? 🌐 API Clients Inject Axios, Fetch wrappers, or GraphQL clients. 🔐 Authentication / Theme Inject user or theme using Context API. 🧪 Testing Replace real payment gateways with mock services. 🏢 Enterprise Apps Swap implementations without touching UI components. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY Dependency Injection is like a Chef and their Tools 👨🍳 The Chef (Component) doesn’t build their own stove (Dependency). The Restaurant Owner (Parent) provides the tools. The Chef only focuses on cooking (UI logic). ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone improving frontend architecture #ReactJS #DependencyInjection #FrontendArchitecture #CleanCode #ScalableApps #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
To view or add a comment, sign in
-
-
🚨 React Native Interview Prep: Stop Memorizing, Start Architecting. I’ve sat on both sides of the interview table. The difference between a Junior and a Senior isn't knowing the syntax—it's understanding the "Why." If you can’t explain how the Bridge works or why a UI freezes during a heavy JS calculation, you aren't ready for that Senior role. Here is the ultimate 2026 React Native Interview Checklist. Save this for your next technical round. 👇 📱 1. The Architecture (The "Under the Hood" Stuff) * What is the Bridge, and how does it differ from the New Architecture (JSI, Fabric)? * Explain the Threading Model: Main Thread vs. JS Thread vs. Shadow Thread. * How does Hermes actually improve startup time? ⚡ 2. Performance & Optimization (The Senior Filter) * FlatList vs. ScrollView: Why does the former win for large datasets? * When does useCallback actually hurt performance instead of helping? * What causes UI Lag, and how do you profile it using Flipper or DevTools? 🧭 3. Navigation & State * How do you structure a secure Auth Flow (Login -> Home)? * Context vs. Zustand vs. Redux: When is Redux "overkill"? * How do you reset the navigation stack on logout to prevent "back-button" bugs? 🛠️ 4. Native & Ecosystem * Expo vs. CLI: Which one do you pick for a high-compliance banking app? Why? * How do you handle Platform-specific code without creating a maintenance nightmare? * What is Deep Linking, and how does the OS handle the intent? 🔥 The "Curveball" Questions * Explain the Event Loop in the context of React Native. * How do you structure a large-scale app to ensure 10+ developers can work on it simultaneously? * Why does a heavy JSON parse freeze the UI, and how do you fix it? 🎯 Pro-Tip from the Field Interviews aren't a quiz; they are a consultation. Don't just give the answer—justify the trade-off. > "I chose Zustand over Redux because the boilerplate was slowing down our feature velocity, and we didn't need complex middleware." > That sentence alone proves more seniority than a 5-minute explanation of Redux Thunk. Which topic should I deep-dive into next? 1️⃣ Detailed Interview Answers 2️⃣ Senior-Level System Design for Mobile 3️⃣ Coding Round Live-Challenge Prep Don’t just memorize the syntax. In a high-stakes interview, they aren't testing your ability to Google—they are testing your clarity of thinking. #ReactNative #MobileDev #SoftwareEngineering #TechInterviews #CareerGrowth #Programming #AppDevelopment #60/ReactNative
To view or add a comment, sign in
-
Real React + TypeScript Interview Scenarios (That Actually Get Asked) Most React + TypeScript interviews don’t test syntax. They test how you think. From typing API responses to fixing real production bugs these are the exact scenarios interviewers use to judge if you can build scalable, safe applications. 1️⃣ Fix Type Errors in a Real Component Scenario: You’re given a component throwing TypeScript errors. They test: Props typing Optional vs required props Union vs interface React.FC vs explicit typing Typical question: > Why is this prop possibly undefined? How would you fix it without using any? They expect: Optional chaining Default values Proper narrowing 2️⃣ Build a Generic Reusable Component Scenario: Create a reusable Dropdown or Table. They test: Generics <T> Typed callbacks Preventing runtime bugs at compile time Follow-up trap: > How do you restrict T to objects with an id? Correct thinking: <T extends { id: string }> 3️⃣ useState with Complex Types const [user, setUser] = useState(null); Works in JS. Problematic in TS. Why? Because TypeScript infers null only. Correct approach: const [user, setUser] = useState<User | null>(null); They’re checking if you understand union types and inference. 4️⃣ API Response Typing (Very Common) Scenario: API may return success or error. They expect discriminated unions: type ApiResponse = | { status: "success"; data: User } | { status: "error"; message: string }; They’ll ask: > How does this prevent runtime crashes? Answer: Safe narrowing based on status. 5️⃣ Event Typing in Forms They expect: const handleChange = ( e: React.ChangeEvent<HTMLInputElement> ) => {} Follow-up: > Difference between SyntheticEvent and native event? If you can answer this clearly you stand out. 6️⃣ useRef Proper Typing Accessing DOM element? const inputRef = useRef<HTMLInputElement | null>(null); They’re checking: Null safety Strict mode awareness 7️⃣ Preventing Re-renders with memo Scenario: Performance issue in large list. They test: React.memo useCallback with typed functions Dependency typing Follow-up: > When can memo make performance worse? If you mention unnecessary comparisons and memory overhead bonus points. 8️⃣ Context API + Type Safety Bad: const ThemeContext = createContext(null); Expected fix: Proper context type Custom hook Runtime guard if (!context) { throw new Error("Must be used within provider"); } 9️⃣ Type vs Interface (They WILL Ask) Question: > When would you prefer type over interface? They expect you to mention: Unions & intersections Utility types Declaration merging 🔟 Real Production Bug Scenario Scenario: Component works locally but crashes in production. #ReactJS #TypeScript #Frontend #ReactDeveloper #WebDevelopment #MERN
To view or add a comment, sign in
-
-
Top Node.js Interview Questions & Answers (Beginner to Advanced Guide) Preparing for a Node.js interview? This guide covers the most frequently asked Node.js interview questions for developers with 1–5+ years of experience, including scenario-based and real-world production questions asked in MNCs and product-based companies. 🔥 Core Node.js Interview Questions ✅ What is Node.js and why is it single-threaded? ✅ How does the Event Loop work? ✅ What are blocking vs non-blocking operations? ✅ What is the difference between process.nextTick() and setImmediate()? ✅ What is the role of V8 engine? ✅ What are Streams in Node.js? ✅ What is middleware in Express.js? ✅ How does Node.js handle concurrency? ✅ What are worker threads? ✅ What is clustering in Node.js? ⚙️ Practical / Scenario-Based Questions • How would you handle high traffic in a Node.js application? • How to prevent blocking the event loop? • How to secure REST APIs? • How to implement authentication (JWT)? • How to handle file uploads? • How to manage environment variables? • Difference between require and ES modules? • How to optimize performance in production? 🧠 Advanced Topics 🔥 Event Loop Phases 🔥 Memory Management 🔥 Streams & Buffers 🔥 Rate Limiting 🔥 Caching (Redis) 🔥 Error Handling Best Practices 🔥 Microservices with Node.js 🎯 Why This Matters? In interviews, companies don’t just test syntax — they test: ✔ Your understanding of the event loop ✔ How Node handles async operations ✔ Your debugging skills ✔ Performance optimization knowledge ✔ Production readiness If you deeply understand Node.js internals, you’ll confidently clear backend interviews. Perfect for: • Backend Developers • Full Stack Developers (MERN) • JavaScript Developers • Developers targeting MNC & product companies #NodeJS #BackendDeveloper #JavaScript #MERNStack
To view or add a comment, sign in
-
React Frontend Interviews in 2026 Are a Different Game If you're still revising: “Difference between useState and useEffect” “What is Virtual DOM?” “Explain lifecycle methods” You're preparing for yesterday’s interviews. The expectations have evolved. Companies no longer want React API users. They want engineers who understand how React behaves internally and why it behaves that way. 🔎 What Interviewers Actually Care About Now ⚙️ React Internals & Scheduling Instead of asking what a hook does, they ask: What happens when multiple state updates are batched? How does React Fiber split work into render and commit phases? What existed before Fiber? How does reconciliation actually decide what to update? Why does StrictMode double-invoke certain logic? What are priority lanes and cooperative scheduling? If you can’t explain scheduling, interruption, and render phases clearly, senior-level roles become difficult. 🧠 Debugging & Performance Thinking Modern interviews simulate production problems: How do you detect memory leaks in React? Why is the UI lagging even though components are small? What is the Critical Rendering Path? When would you use Web Workers? Why use AbortController in data fetching? It’s less about building UI. It’s more about fixing real-world issues. 🏗️ Architecture & System Design You’ll face questions like: How do two components communicate without props, Redux, or Context? When does middleware make sense on the frontend? JWT vs session-based authentication — trade-offs? REST vs GraphQL integration differences? How do SOLID principles translate into React architecture? Why were HOCs and Render Props used before Custom Hooks? This tests reasoning — not memorization. 🔐 Security Is Now Frontend Responsibility You’re expected to know: How to prevent XSS How to mitigate CSRF Secure token storage strategies Safe data handling in SPAs Security awareness is no longer optional. 🧱 Engineering Principles Matter You should be able to apply: Clean component architecture Separation of concerns And explain how they shape your React codebase. 📌 The 2026 Interview Pattern ❌ Fewer textbook definitions ❌ Fewer “what is this hook” questions ✅ More debugging scenarios ✅ More architectural trade-offs ✅ More performance deep-dives ✅ More “why does this happen?” 🎯 The Real Shift React developers are becoming: • Frontend Engineers • Performance Engineers • UI Architects • Platform Engineers If you want to stay relevant, stop memorizing hooks. Start understanding the rendering engine. The real differentiator in 2026 is depth. Not “What does this API do?” But “Why does this behavior exist?” 👉 Follow Rahul R Jain for more real interview insights, React fundamentals, and practical frontend engineering content. #ReactJS #FrontendEngineering #SystemDesign #WebPerformance #SoftwareArchitecture #TechCareers #UIEngineering #JavaScript
To view or add a comment, sign in
-
Preparing for Full-Stack Developer interviews (0–2 YOE) in 2026? I compiled 50 commonly asked questions across frontend, backend, databases, and system design that appear frequently in interviews. Frontend (React / JS) What is the Virtual DOM? Difference between useEffect and useLayoutEffect What are controlled vs uncontrolled components? What is memoization in React? What is the difference between var, let, and const? Explain closures in JavaScript. What is event delegation? What are promises and async/await? What is the difference between == and ===? What are React hooks? Backend (Node.js / APIs) 11. What is the event loop in Node.js? 12. Difference between synchronous and asynchronous code. 13. What is middleware in Express/Fastify? 14. REST vs GraphQL. 15. What is rate limiting? 16. What is JWT authentication? 17. What is CORS and why is it needed? 18. What is idempotency in APIs? 19. What are HTTP status codes? 20. How do you handle errors in APIs? Databases (SQL / NoSQL) 21. SQL vs NoSQL databases. 22. What is indexing in databases? 23. What is normalization? 24. What are ACID properties? 25. What are database transactions? 26. What is a JOIN? 27. What is a composite index? 28. Difference between primary key and unique key. 29. What is query optimization? 30. What is database sharding? System Design Basics 31. How would you design a URL shortener? 32. How would you design a chat system? 33. What is caching? 34. What is load balancing? 35. What is horizontal vs vertical scaling? 36. What is a CDN? 37. What is message queue (Kafka/RabbitMQ)? 38. What is eventual consistency? 39. What is microservices architecture? 40. What is API gateway? General Engineering 41. What is Docker and why use it? 42. What is CI/CD? 43. What is Git rebase vs merge? 44. What are environment variables? 45. What is logging vs monitoring? 46. What is clean code? 47. What is SOLID principle? 48. What is code review? 49. What is technical debt? 50. What is scalability? If you're preparing for interviews, mastering these fundamentals can cover a large portion of real interview discussions. Which question do you think is most commonly asked in interviews? #SoftwareEngineering #FullStackDeveloper #TechInterviews #Programming #WebDevelopment 🚀
To view or add a comment, sign in
-
-
⚛️ Top 150 React Interview Questions – 147/150 📌 Topic: 🛑 Stale Closures in React ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? A Stale Closure happens when a function captures a variable from an old render and keeps using that outdated value. In React: Every render creates a new scope. If a function is created once and never updated, it keeps referencing the old state. Closure = Snapshot of variables at creation time. If not refreshed → it becomes stale. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY does it happen? 🧠 Environment Locking JavaScript closures freeze the scope they were created in. ⚠️ Logic Errors Timers or handlers read outdated values → UI feels broken. 📦 Hook Dependency Rules This is exactly why dependency arrays exist in useEffect and useCallback. Ignoring dependencies = stale data risk. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW does it occur? Classic mistake: const [count, setCount] = useState(0); useEffect(() => { const id = setInterval(() => { // ❌ STALE: 'count' is always 0 console.log(count); }, 1000); return () => clearInterval(id); }, []); // Empty dependency array Here: • Effect runs only once • Closure captures count = 0 • Interval never sees updated state ✅ Fix 1: Add Dependency useEffect(() => { const id = setInterval(() => { console.log(count); }, 1000); return () => clearInterval(id); }, [count]); ✅ Fix 2: Use Functional Update setCount(c => c + 1); Functional updates always use the latest value. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE does this bug appear? ⏱ Intervals & Timeouts setInterval reading outdated state. 🌍 Manual Event Listeners window.addEventListener referencing old values. 🧩 useCallback / useMemo Memoized functions missing dependencies. Any long-lived function = risk of stale closure. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY A Stale Closure is like Navigating with an Old Map 🗺️ You’re using a map from 1990 (old render) to find a building built in 2026 (current state). The map is stuck in time. So you reach the wrong destination. Always update your map (Dependencies). ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone mastering React hooks #ReactJS #StaleClosures #useEffect #JavaScriptClosures #FrontendDebugging #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
To view or add a comment, sign in
-
-
🚀 Frontend Interview Experience (4.5 Years Exp)! I attended a frontend interview and wanted to share the questions I was asked so it can help others who are preparing. These questions tested practical knowledge, fundamentals, and real-world thinking. 👇 Topics Covered: 1️⃣ Lazy Loading – Explained concept + wrote implementation code 2️⃣ Top 5 React Hooks – useState, useEffect, useMemo, useCallback, useRef with use-cases 3️⃣ Handling Large API Data – Pagination, virtualization, memoization, caching strategies 4️⃣ Optimizing Large Projects – Code splitting, bundle analysis, lazy imports, performance tuning 5️⃣ JS Output Questions • console.log(1 + 2) • console.log(1 + "2") • console.log(1 + A) 6️⃣ Difference between == and === 7️⃣ Async vs Synchronous execution 8️⃣ Async/Await concept + real use scenario 9️⃣ Difference between AI and Generative AI 🔟 What are LLMs and SLMs 1️⃣1️⃣ System design approach for very large frontend applications 1️⃣2️⃣ Difference between null and undefined 1️⃣3️⃣ Difference between class and id in CSS 1️⃣4️⃣ Difference between Server-Side Rendering (SSR) and Client-Side Rendering (CSR) 💡 Key Learning: Interviews today are not about memorizing definitions. They evaluate: Real project experience Optimization thinking Core JavaScript fundamentals Architecture mindset Problem-solving ability 📌 Preparation Tip: If you're preparing for frontend interviews, focus on: ✔ JavaScript fundamentals ✔ Performance optimization ✔ React internals ✔ System design basics ✔ Writing clean, scalable code hashtag#Frontend hashtag#InterviewPrep hasht
To view or add a comment, sign in
-
I have just launched a dedicated blog packed with React Native Interview Questions & Answers - designed to help developers ace their interviews and level up their skills. Whether you're a beginner or have 1+ years of experience, this page covers : ➡️ Core React Native concepts ➡️ Hooks, State, and Component ➡️ Redux & State Management ➡️ FlatList, ScrollView and UI essentials ➡️ Coding examples and real-world scenarios
To view or add a comment, sign in
-
React interviews are no longer about “what is useEffect?” If you’re preparing for React LLD rounds, practice like this 👇 1. Toast / Notification System - Design queue + stacking logic. - Auto-dismiss with timers. - Support variants like success, error, warning without hardcoding styles. 2. Infinite Scroll - Handle pagination, loading, retry states. - Choose wisely: Intersection Observer (cleaner) vs scroll listeners (manual control). - Avoid duplicate fetches. 3. Reusable Data Fetching Hook (with Cache) - Prevent duplicate API calls. - Support background refresh. - Optimistic updates without breaking UI consistency. 4. Real-Time Chat UI - Correct message ordering. - Deduplicate events. - Typing indicators + delivery/read status. - Chat history with upward infinite scroll. 5. File Uploader with Progress - Chunk large files. - Pause / cancel / retry uploads. - Preview + validation before upload. 6. List Virtualization (from scratch) - Render only visible items. - Handle fixed vs variable heights. - Maintain stable scroll position on data updates. 7. Accessible Modal - Escape key + outside click handling. - Focus trap. - Lock background scroll cleanly. 8. Global State (No Libraries) - Context + useReducer architecture. - Async flows. - Logging / middleware-style pattern. 9. Multi-Step Form - Persist state between steps. - Save progress. - Resume later without losing data. 10. Image Lazy Loading - Detect viewport entry. - Compare blur vs skeleton vs shimmer placeholders. - Retry failed loads. 11. Large List Performance - Memoization strategy. - Avoid unnecessary re-renders. - Component-level code splitting. 12. Debounced Search - Cancel stale API requests. - Cache previous results for instant UX. 13. Data Grid System - Client vs server-side trade-offs. - Minimize re-renders. - Dynamic columns + layout configs. 14. Real-Time Form Validation - Rule modeling. - Conditional inputs. - Dynamic schema changes. 15. Drag & Drop Reordering - Visual feedback while dragging. - Touch + keyboard accessibility. - Stable state updates. This is what modern frontend interviews look like. Not syntax. Not definitions. Architecture + trade-offs + performance thinking. If you’re serious about cracking interviews, combine strong React LLD with solid DSA foundations. I’ve structured my DSA Guide exactly around interview patterns. For DSA Prep: ✅ Notes that are concise and clear ✅ Most-asked questions ✅ Real patterns + approaches 👉 Get the DSA Guide → https://lnkd.in/d8fbNtNv (450+ devs are already using) Get 25% Off Now : DEV25 For ReactJS Prep: ✅ Handwritten notes for quick revision ✅ Interview-focused concepts explained simply ✅ Covers fundamentals + advanced topics developers miss 👉 Get the React Guide → https://lnkd.in/dpDy_i2W 𝐅𝐨𝐫 𝐌𝐨𝐫𝐞 𝐃𝐞𝐯 𝐈𝐧𝐬𝐢𝐠𝐡𝐭𝐬 𝐉𝐨𝐢𝐧 𝐌𝐲 𝐂𝐨𝐦𝐦𝐮𝐧𝐢𝐭𝐲: Telegram → https://lnkd.in/d_PjD86B Whatsapp → https://lnkd.in/dvk8prj5 Built for devs who want to crack interviews — not just solve problems.
To view or add a comment, sign in
Explore related topics
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development