⚛️ 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 ━━━━━━━━━━━━━━━━━━━━━━
React Cleanup Function: Preventing Memory Leaks and Errors
More Relevant Posts
-
⚛️ 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
-
-
🚀 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
-
🚀 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
-
Node.js interviews are getting more competitive — but the right questions can boost your confidence instantly. Here's a complete list of 50 Node.js interview questions that every backend developer should practice before the next opportunity. Save this ✔ Share this 🔁 Upgrade your preparation 💯 ⭐ TOP 50 NODE.JS INTERVIEW QUESTIONS 1. What is Node.js? 2. What is NPM? 3. What is the Event Loop in Node.js? 4. What is Non-Blocking I/O? 5. What are Node.js Modules? 6. What is CommonJS? 7. What is the difference between require() and import? 8. What is Express.js? 9. What is Middleware in Express? 10. What is package.json? 11. What is a callback? 12. What is callback hell? 13. What is a Promise? 14. What is async/await? 15. What are Streams in Node.js? 16. What is a Buffer? 17. What is the difference between process.nextTick() and setImmediate()? 18. What is the difference between Node.js and JavaScript? 19. What are the types of Node.js APIs? 20. What is the difference between spawn() and fork()? 21. What is clustering in Node.js? 22. What is REPL in Node.js? 23. What is the difference between readFile() and createReadStream()? 24. What is process.env? 25. What is the difference between PUT and PATCH? 26. How do you handle errors in Node.js? 27. What is CORS? 28. What is JWT? 29. What is the difference between synchronous and asynchronous code? 30. How do you debug Node.js applications? 31. What is the difference between HTTP and HTTPS? 32. What is a REST API? 33. What is the difference between process.on('exit') and process.on('beforeExit')? 34. What is the difference between res.send() and res.json()? 35. How do you handle file uploads in Node.js? 36. What is the difference between cluster and worker threads? 37. What is the difference between setTimeout() and setInterval()? 38. What is the difference between Cluster and PM2? 39. How does Node.js handle child processes? 40. What is the difference between synchronous and asynchronous file operations? 41. What is a template engine in Node.js? 42. What is Node.js REPL? 43. What is the difference between local and global modules? 44. What is the difference between cluster.fork() and child_process.fork()? 45. What are Node.js timers? 46. What is the difference between cluster module and worker_threads module? 47. What is process.argv? 48. How does Node.js handle memory management? 49. What is the difference between require() and require.resolve()? 50. What is the difference between Node.js and PHP? #Nodejs #JavaScript #BackendDeveloper #InterviewPrep #Coding #Developers #WebDevelopment #MERNStack #TechJobs #SoftwareEngineering #ProgrammingTips
To view or add a comment, sign in
-
Product-based companies for frontend roles tend to ask interview questions that have real-world use cases. One such question was asked in META's (Facebook) interview, where it was asked to implement Test() and expect() as in the Jest testing library. Looks simple, but it is extremely challenging given the fact that for each assertion, you have to support negation as well as chaining. expect(undefined).toBeUndefined(); expect(undefined).not.toBeUndefined(); Also, how to keep it extensible to support adding custom assertion methods. On the alpha[.]learnersbucket[.]com, I have around 500+ frontend interview questions from 32 different product-based companies. Enroll today and get lifetime access to the best frontend interview preparation resource.
To view or add a comment, sign in
-
-
Product-based companies for frontend roles tend to ask interview questions that have real-world use cases. One such question was asked in META's (Facebook) interview, where it was asked to implement Test() and expect() as in the Jest testing library. Looks simple, but it is extremely challenging given the fact that for each assertion, you have to support negation as well as chaining. expect(undefined).toBeUndefined(); expect(undefined).not.toBeUndefined(); Also, how to keep it extensible to support adding custom assertion methods. On the alpha[.]learnersbucket[.]com, I have around 500+ frontend interview questions from 32 different product-based companies. Enroll today and get lifetime access to the best frontend interview preparation resource.
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
-
🚀 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
-
-
💻 A Full-Stack interview experience that reminded me why fundamentals matter. Recently, during a conversation with a friend who appeared for a Full-Stack Developer interview, something interesting came up. He expected the interview to focus heavily on frameworks like React, Node.js, and modern tools. But the interviewer took a different direction. Instead of asking only about frameworks, the discussion moved toward fundamentals of frontend and backend development. Questions started appearing from different areas: JavaScript concepts. React fundamentals. API design. Authentication. Database understanding. That moment made one thing very clear: In Full-Stack interviews, companies often test how well you understand the core concepts behind the technology, not just the frameworks you use. Here are some common Frontend & Backend questions that often come up in Full-Stack interviews: 🎨 Frontend Questions 1️⃣ What is the difference between var, let, and const in JavaScript? 2️⃣ What is the Virtual DOM and how does it work in React? 3️⃣ What are React Hooks and why are they important? 4️⃣ What is the difference between useEffect and useLayoutEffect? 5️⃣ What are controlled vs uncontrolled components? 6️⃣ What is state management and when would you use Redux or Context API? 7️⃣ What is the difference between Flexbox and Grid in CSS? 8️⃣ How does event bubbling and event capturing work in JavaScript? 9️⃣ What are memoization techniques in React (React.memo, useMemo)? 🔟 How do you optimize performance in a frontend application? ⚙️ Backend Questions 1️⃣ What is the difference between REST and GraphQL APIs? 2️⃣ What is middleware in backend frameworks like Express.js? 3️⃣ What is the difference between authentication and authorization? 4️⃣ What are HTTP status codes and why are they important? 5️⃣ What is JWT (JSON Web Token) and how does it work? 6️⃣ What is the difference between SQL and NoSQL databases? 7️⃣ How do you handle errors in backend applications? 8️⃣ What is caching and why is it used? 9️⃣ What is the difference between synchronous and asynchronous programming? 🔟 How do you secure an API? Preparing frameworks is important. But interviews often go deeper than that. Sometimes the most important thing you can prepare is a strong understanding of the basics. 💬 Curious to hear from other developers: What was the most unexpected question you were asked in a Full-Stack interview? #FullStack #webdevelopment #frontend #backend #interviewexperience #softwareengineering #developers #learning
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