⚛️ 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 ━━━━━━━━━━━━━━━━━━━━━━
React Interview Question: Stale Closures in React
More Relevant Posts
-
⚛️ Top 150 React Interview Questions – 146/150 📌 Topic: 🧹 Cleanup Function Importance ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? The Cleanup Function is the function returned inside useEffect. It runs: • Right before a component unmounts • Before the effect re-runs (when dependencies change) Its job is to undo side effects created by the effect. Think of it as a reset mechanism. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY is it critical? 🧠 Prevents Memory Leaks Stops timers, subscriptions, or listeners from running after unmount. ⚠️ Avoids Illegal State Updates Prevents “Cannot update state on an unmounted component” errors. 🔒 System Integrity Releases global resources like WebSockets and browser listeners. Without cleanup → background chaos. With cleanup → controlled environment. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW does it work? React automatically executes the returned function. ✅ WebSocket Cleanup useEffect(() => { const socket = connect(id); // CLEANUP return () => socket.disconnect(); }, [id]); When id changes or component unmounts → connection closes. ✅ Abort API Request useEffect(() => { const controller = new AbortController(); fetch(url, { signal: controller.signal }); return () => controller.abort(); // Cancel request }, [url]); Prevents updating state after navigation. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE is cleanup mandatory? 🔌 Subscriptions WebSocket, Firebase, Chat APIs. 🌍 Browser APIs window.addEventListener (scroll, resize). ⏱ Timers clearTimeout / clearInterval. 📡 Async Requests AbortController for pending fetch calls. Any persistent side effect → requires cleanup. ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY The Cleanup Function is like Checking Out of a Hotel Room 🏨 Before leaving (Unmount), you must turn off lights and close taps. If you don’t, the hotel (Browser) keeps wasting resources. Cleanup ensures nothing is left running after you leave. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this series is helping you 🔁 Share with someone mastering useEffect #ReactJS #useEffect #MemoryLeaks #FrontendBestPractices #WebPerformance #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
To view or add a comment, sign in
-
-
🚀 React Interview Questions Asked in recent interview (For Mid–Senior Frontend Developers) During interviews, many React questions are not about definitions but about understanding how React behaves internally. Here are some commonly asked questions along with clear explanations. 1️⃣ Multiple components are rendering and the app becomes slow — why? When multiple components re-render frequently, performance can degrade. This usually happens because React re-renders a component whenever its state or props change. Common causes: Parent component re-renders, causing all child components to re-render. Passing new object/array references in props. Inline functions created on every render. Expensive computations inside render. Example problem: <Child data={{ name: "John" }} /> Even if the value is the same, a new object reference is created on every render, so React treats it as a change. Solutions: Use React.memo for child components. Avoid inline objects/functions. Memoize values with useMemo. Memoize callbacks with useCallback. 2️⃣ Dependency array exists in useEffect, but I still want to avoid unnecessary re-renders Important concept: useEffect does not control rendering. Rendering happens because of state or prop changes, not because of useEffect. Example: useEffect(() => { fetchData(); }, [userId]); This only controls when the effect runs, not when the component renders. Ways to reduce unnecessary renders: Avoid unnecessary state updates Use React.memo Use useMemo / useCallback Lift state only when needed 3️⃣ What is Hydration in React? Hydration is mainly used in server-side rendering frameworks like Next.js. Steps: Server renders HTML. Browser receives fully rendered HTML. React attaches event listeners and makes it interactive. Example flow: Server: HTML sent to browser Client: React attaches JS behavior to existing HTML This process is called hydration. If the server HTML and client render output differ, React throws a hydration mismatch warning. Common causes: Random values Date/time differences Browser-only APIs 4️⃣ React Strict Mode in Development vs Production React.StrictMode is a development tool. Development behavior: Components render twice intentionally Helps detect side effects Warns about unsafe lifecycle methods Important point: Strict Mode does NOT affect production. Double rendering happens only in development. Purpose: Detect bugs early Ensure components are resilient 5️⃣ Same hook behaves differently in two sibling components — why? Hooks are isolated per component instance. Example: <ComponentA /> <ComponentB /> Even if both use the same hook: const [count, setCount] = useState(0); Each component maintains its own independent state. Possible reasons behavior differs: Different props Different lifecycle timing Conditional rendering Parent re-rendering one child more often #ReactJS #FrontendDevelopment #JavaScript #ReactInterview #WebDevelopment #NextJS #SoftwareEngineering #FrontendEngineer #ReactHooks #CodingInterview
To view or add a comment, sign in
-
🚀 React Interview: How I would answer this question step-by-step Question: 👉 “How would you optimize a slow React application?” Most developers jump straight to answers. But here’s how I approach it 👇 --- 🌲 Step 1: Understand the problem Is it slow on initial load or during interactions? --- 🌲 Step 2: Identify bottlenecks Use React DevTools Profiler to find unnecessary re-renders --- 🌲 Step 3: Fix re-render issues Use React.memo, useMemo, useCallback where needed --- 🌲 Step 4: Optimize rendering Apply code splitting and lazy loading --- 🌲 Step 5: Handle large data Use virtualization (react-window / react-virtualized) --- 🌲 Step 6: Optimize API calls Debounce, throttle, and cache responses --- 🌲 Step 7: Check bundle size Remove unused libraries, use tree-shaking --- 💡 Most candidates fail because they don’t structure their answers like this. 👉 Interviews are not just about knowledge, but clear thinking Curious to know 👇 👉 How would YOU approach this question? If you're preparing for Frontend / React interviews, I also help with: ✅ Mock Interviews ✅ Resume Review ✅ Interview Preparation Strategy ✅ Real-world React concepts Book a session here 👇 🚀 Topmate: https://lnkd.in/d9EuJiwV
To view or add a comment, sign in
-
🚀 Day 19/100 – #100DaysOfCode React Interview Preparation (useState & useEffect) Focusing on two of the most commonly asked React interview topics: useState and useEffect. These hooks are fundamental for managing state and handling side effects in React applications. 🔹 useState useState is a React hook that allows functional components to store and manage state. Key points often asked in interviews: -It allows components to remember values between renders. -Updating state using the setter function triggers a re-render. -The hook returns two values: the state and a function to update it. -State updates should be immutable and not modified directly. Example concept: const [count, setCount] = useState(0); 🔹 useEffect useEffect is used to handle side effects in React components, such as: -Fetching data from APIs -Updating the DOM -Setting up timers -Subscribing to events Important interview points: -It runs after the component renders. -The dependency array controls when the effect runs. -An empty dependency array ([]) runs the effect only once (similar to componentDidMount). -It can also return a cleanup function to prevent memory leaks. Example concept: useEffect(() => { fetchData(); }, []); Almost every React application relies on them for managing state and side effects. #Day19 #100DaysOfCode #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #WebDevJourney #LearningInPublic
To view or add a comment, sign in
-
-
🚀 **Node.js Interview Series — Day X** 📌 **Difference between `app.use()` and `app.get()` in Express** Understanding this is 🔑 for backend interviews! ⚙️ **app.use() (Middleware)** ✔️ Runs for ALL HTTP methods (GET, POST, etc.) ✔️ Works on all or prefix routes ✔️ Used for logging, auth, validation ✔️ Requires `next()` to pass control 🚀 **app.get() (Route Handler)** ✔️ Runs only for GET requests ✔️ Matches a specific route ✔️ Sends response to client ✔️ Ends request cycle 💡 Example: ```js app.use((req, res, next) => { console.log("Middleware"); next(); }); app.get("/users", (req, res) => { res.send("Users list"); }); ``` 🔥 **Interview Tip:** Use `app.use()` for reusable logic Use route handlers (`app.get()`, etc.) for actual endpoints Follow for more Node.js interview questions 🚀 #NodeJS #ExpressJS #BackendDevelopment #InterviewPrep #JavaScript
To view or add a comment, sign in
-
-
💡 23 Advanced React Scenario-Based Interview Questions While preparing for frontend interviews, I noticed companies rarely ask only theory. They prefer real production scenarios to test how you think as a React developer. Here are 23 advanced React scenarios often asked in interviews: 1️⃣ A component keeps re-rendering infinitely after adding a "useEffect". What could cause this? 2️⃣ A child component is re-rendering even when props didn’t change. How would you debug it? 3️⃣ Your application becomes slow when rendering a large list (1000+ items). What would you do? 4️⃣ You fetch data inside "useEffect", but sometimes the API call happens twice in development. Why? 5️⃣ A component updates state but the UI doesn’t update immediately. Why might that happen? 6️⃣ Multiple components need the same data from an API. How would you manage this efficiently? 7️⃣ A user navigates away before an API finishes and React shows a memory leak warning. How do you fix it? 8️⃣ A parent passes a function to a child component and it causes unnecessary renders. Why? 9️⃣ You have a form with many inputs and performance starts degrading. What strategy would you use? 🔟 Two components need to share state but are far apart in the component tree. How would you solve it? These types of questions test your understanding of: ⚡ Performance optimization ⚡ State management ⚡ React lifecycle & hooks ⚡ Real-world debugging If you’re preparing for React interviews, practicing scenario-based questions like these helps a lot. #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #TechInterview #WomenInTech #ReactDeveloper #CodingInterview
To view or add a comment, sign in
-
🚀 **Want to Crack a React Job Interview? Read This.** After going deep into multiple React interviews, here’s what truly matters 👇 It’s NOT just “I know React.” It’s mastery of **JavaScript fundamentals + React internals + real-world architecture thinking.** -- ## 🔥 Step 1: JavaScript Must Be Rock Solid If your JS basics are weak, React interviews become difficult. Make sure you can confidently explain and code: ✔ let vs var vs const ✔ Rest vs Spread (with real examples) ✔ map vs forEach ✔ splice vs slice ✔ || vs ?? ✔ Closures, currying, memoization ✔ Debounce & Throttle (from scratch) ✔ Polyfills (map, reduce, bind) ✔ Event loop (microtasks vs macrotasks) ✔ Promise.all vs allSettled vs race ✔ Deep vs shallow copy ✔ this, bind/call/apply ✔ Hoisting ✔ ES6 modules If you can’t implement debounce without Google, you’re not interview-ready yet. --- ## ⚛ Step 2: React Core Understanding (Not Just Hooks) Interviewers test concepts like: ✔ How React actually works ✔ Virtual DOM & Reconciliation ✔ React Fiber architecture ✔ Why React is fast ✔ React 18 concurrent features ✔ Batching ✔ Suspense ✔ SSR vs CSR ✔ Code splitting ✔ Tree shaking ✔ Rendering behavior If you only know `useState` and `useEffect`, that’s junior-level. --- ## 🧠 Step 3: Hooks & Performance Mastery Be clear about: ✔ useEffect lifecycle patterns ✔ useLayoutEffect vs useEffect ✔ useMemo vs useCallback ✔ React.memo ✔ Custom hooks & hook rules ✔ Controlled vs uncontrolled forms ✔ Lifting state & avoiding prop drilling ✔ Context API vs Redux You should explain WHEN and WHY — not just HOW. --- ## 🏗 Step 4: Architecture & System Design For 3–5+ years experience roles, expect: ✔ How to structure large React apps ✔ Folder structure decisions ✔ Client-side caching strategy ✔ Offline-first apps ✔ Core Web Vitals optimization ✔ Designing reusable modal/toast systems ✔ Real-time dashboards ✔ Component libraries used by multiple teams This is where most candidates struggle. --- ## 🧪 Step 5: Testing Knowledge ✔ Jest ✔ React Testing Library ✔ Mocking APIs ✔ Unit vs Integration vs E2E ✔ Cypress / Playwright basics Companies care about production readiness. --- ## 💻 Step 6: Machine Coding Rounds Common tasks: • Infinite scroll • Autocomplete • Accordion / Modal / Carousel • Star rating • Grid with search & sort • Event bubbling scenarios • Implement throttle • Tic-tac-toe Speed + clean logic matters. --- ### 🎯 Final Advice Most React interviews are actually: > 60% JavaScript > 30% React concepts > 10% System design Master fundamentals first. React is easy. JavaScript depth is what separates average from strong candidates. --- If this helps, comment “React” and I’ll share a structured 30-day preparation roadmap. 💪 or Want to prepare for the interview connect with me.
To view or add a comment, sign in
-
🚀 15 Node.js Interview Questions Every Developer Should Know If you're preparing for Node.js interviews or building backend systems, these questions are commonly asked 👇 1️⃣ What is Node.js? Node.js is a JavaScript runtime built on the V8 engine that allows developers to run JavaScript on the server side. 2️⃣ What is the Event Loop in Node.js? The Event Loop handles asynchronous operations and allows Node.js to manage multiple requests without blocking the main thread. 3️⃣ What is the difference between "setTimeout()" and "setImmediate()"? • "setTimeout()" executes after a specified delay. • "setImmediate()" executes in the next event loop cycle. 4️⃣ What are Streams in Node.js? Streams process data piece by piece instead of loading the entire data in memory. 5️⃣ What is Middleware in Express.js? Middleware functions run between request and response and can modify data, handle authentication, or log requests. 6️⃣ What is the difference between "process.nextTick()" and "setImmediate()"? "process.nextTick()" runs before the event loop continues, while "setImmediate()" runs in the next iteration. 7️⃣ What is the "cluster" module? It allows Node.js applications to use multiple CPU cores by creating worker processes. 8️⃣ What is "package.json"? It contains project metadata, dependencies, scripts, and configuration. 9️⃣ What is "package-lock.json"? It locks dependency versions to ensure consistent installations across environments. 🔟 What is the difference between "require()" and "import"? • "require()" → CommonJS modules • "import" → ES Modules syntax 1️⃣1️⃣ What is error-first callback in Node.js? A callback pattern where the first argument is an error object. Example: fs.readFile("file.txt", (err, data) => { if (err) throw err; console.log(data); }); 1️⃣2️⃣ What are Buffers in Node.js? Buffers are used to handle binary data such as images, videos, and file streams. 1️⃣3️⃣ What is the difference between synchronous and asynchronous functions? • Synchronous → executes line by line and blocks execution. • Asynchronous → runs in the background without blocking the main thread. 1️⃣4️⃣ What is REST API in Node.js? A REST API allows communication between client and server using HTTP methods like GET, POST, PUT, DELETE. 1️⃣5️⃣ What is CORS? CORS (Cross-Origin Resource Sharing) allows servers to specify which domains can access their APIs. 💡 Pro Tip: If you understand Event Loop + Async patterns + Streams + Scaling, you’re already thinking like a senior Node.js developer. 🔥 Save this post for your next backend interview. #NodeJS #BackendDevelopment #JavaScript #WebDevelopment #SoftwareEngineering
To view or add a comment, sign in
-
💡 23 Advanced React Scenario-Based Interview Questions While preparing for frontend interviews, I noticed companies rarely ask only theory. They prefer real production scenarios to test how you think as a React developer. Here are 23 advanced React scenarios often asked in interviews: 1️⃣ A component keeps re-rendering infinitely after adding a "useEffect". What could cause this? 2️⃣ A child component is re-rendering even when props didn’t change. How would you debug it? 3️⃣ Your application becomes slow when rendering a large list (1000+ items). What would you do? 4️⃣ You fetch data inside "useEffect", but sometimes the API call happens twice in development. Why? 5️⃣ A component updates state but the UI doesn’t update immediately. Why might that happen? 6️⃣ Multiple components need the same data from an API. How would you manage this efficiently? 7️⃣ A user navigates away before an API finishes and React shows a memory leak warning. How do you fix it? 8️⃣ A parent passes a function to a child component and it causes unnecessary renders. Why? 9️⃣ You have a form with many inputs and performance starts degrading. What strategy would you use? 🔟 Two components need to share state but are far apart in the component tree. How would you solve it? These types of questions test your understanding of: ⚡ Performance optimization ⚡ State management ⚡ React lifecycle & hooks ⚡ Real-world debugging If you’re preparing for React interviews, practicing scenario-based questions like these helps a lot. 👨💻 Follow for daily React, and JavaScript 👉 Arun Dubey #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #TechInterview #ReactDeveloper #CodingInterview
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
-
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