React Interview Question: What happens when setState is called? 💡 setState is used to update the state of a component but it doesn’t update immediately. 🔹 What actually happens when setState is called: - react schedules the state update (it doesn’t update instantly) - multiple setState calls may be batched for performance - react triggers the reconciliation process (Virtual DOM diffing) - only the changed parts of the UI are updated in the real DOM 🔹Key points to keep in mind: - setState is asynchronous (in most cases) - It may batch multiple updates together - It triggers a re-render of the component - react updates only what’s necessary (efficient DOM updates) 🔹State Update Patterns in React This pattern belongs to class components, not hooks setState({ count: count + 1 }); --> //Invalid in hooks In hooks, use the state setter function setCount(count + 1); //basic update setCount(prev => prev + 1); // functional update (recommended for safety) In class components: this.setState({ count: this.state.count + 1 }); //direct update this.setState(prev => ({ count: prev.count + 1 })); // functional update (preferred) Connect/Follow Tarun Kumar for more tech content and interview prep #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #InterviewPrep
React setState behavior and update patterns
More Relevant Posts
-
React Fundamental Interview Question: What is the purpose of the key prop in React? This is one of the most commonly asked questions and also one of the most confusing. Key prop helps React identify which items in a list have changed, been added, or removed. 🔹 Why is key prop important? When rendering lists, React uses a diffing algorithm (reconciliation) to update the UI efficiently. Without a key, React can: - re-render unnecessary elements - update the wrong DOM nodes - cause unexpected UI bugs 🔹 Example (Incorrect way): {items.map((item, index) => ( <li key={index}>{item.name}</li> ))} Using index as a key can break things when: - items are added - items are removed - items are reordered 🔹 Correct way: {items.map((item) => ( <li key={item.id}>{item.name}</li> ))} - use a unique and stable identifier - helps React track elements correctly - improves performance and prevents bugs 🔹 Real-world impact Imagine a list of inputs. If you use index as a key and remove an item, values can shift incorrectly, leading to UX issues. Connect/Follow Tarun Kumar for more tech content and interview prep #ReactJS #FrontendDevelopment #WebDevelopment #JavaScript #ReactInterview #CodingInterview #SoftwareEngineering
To view or add a comment, sign in
-
React Interview Questions that 90% of candidates can’t answer Everyone prepares: useState ✅ useEffect ✅ Virtual DOM ✅ But senior interviews? They go way deeper. Here are the questions that actually separate good from great 👇 1️⃣ setState inside useEffect (no dependency array) Most say: “infinite loop” But real question is: 👉 Why does React’s render cycle cause it? 2️⃣ What is “Tearing” in React? Happens when UI shows inconsistent state during async rendering 👉 This is where Concurrent features come in 3️⃣ useEffect vs useLayoutEffect (real use case) Not just timing… m 👉 Can you explain when to use which in production? 4️⃣ Can you build React without a bundler? 👉 Tests your understanding of ESModules, CDN imports, internals 5️⃣ Zombie Child problem (React-Redux) 👉 When components access stale or deleted state Can you prevent it? 6️⃣ Why not define components inside components? 👉 Breaks reconciliation 👉 Causes subtle re-render bugs 7️⃣ Stale Closure problem in Hooks 👉 When your effect reads old state values Fix? • Correct dependencies • Functional updates 8️⃣ React Portals (real usage) 👉 Not just definition Where would you actually use them? (Modals, tooltips, escaping overflow issues) 9️⃣ Can React work without JSX? 👉 Yes — React.createElement Understanding this = understanding React internals 🔟 Hydration in React / Next.js 👉 Why do hydration errors happen? 👉 How does SSR + client mismatch break UI? 💡 Reality check: Most candidates recognize these terms. Very few can explain them deeply. And that’s exactly what senior interviews test. If you’re preparing… Don’t just learn React. Understand how React works under the hood. Which of these questions caught you off guard? 👇 #React #Frontend #JavaScript #CodingInterview #NextJS #SoftwareEngineering
To view or add a comment, sign in
-
React interviews be like: “Let’s start with something simple…” 😄 5 minutes later… Explain reconciliation. Why is useEffect running twice? How does React decide to re-render? What are keys and why did your app just break? If you’re preparing, here are the React topics that show up everywhere 👇 🧠 The “I thought I knew this” topics • Virtual DOM & reconciliation • Component re-rendering logic • Keys (and why bad keys cause chaos) • Controlled vs uncontrolled components ⚡ Hooks (favorite interview weapon) • useState batching & updates • useEffect (dependencies, cleanup, infinite loops 😅) • useMemo vs useCallback • When NOT to use hooks 🚀 Performance (where candidates struggle) • Preventing unnecessary re-renders • React.memo and memoization • Handling large lists (virtualization) • Code splitting & lazy loading 🏗 Architecture & State Management • Lifting state vs global state • Context vs Redux vs Zustand • Component design patterns • Separation of concerns 🔥 Real-world thinking • How would you optimize a slow React app? • How do you structure a scalable project? • How do you handle API states (loading/error/success)? 💡 Reality check: Everyone knows how to use React. Very few understand how React works. That’s exactly what interviews test. So next time someone says “Let’s start with something simple…” Be ready 😄 Which React topic surprised you the most in interviews? 👇 #React #Frontend #JavaScript #CodingInterview #SoftwareEngineering #WebDevelopment
To view or add a comment, sign in
-
🚀 Top 10 React Basic Interview Questions 🔹 1. What is useState? - > used to manage state in functional components const [count, setCount] = useState(0); 🔹 2. What is useEffect? -> handles side effects (API calls, subscriptions) useEffect(() => { console.log("Component Mounted"); }, []); 🔹 3. How to handle forms in React? (Controlled Components) const [input, setInput] = useState(""); <input value={input} onChange={e => setInput(e.target.value)} /> 🔹 4. How to fetch API data? useEffect(() => { fetch("/api") .then(res => res.json()) .then(data => console.log(data)); }, []); 🔹 5. What is conditional rendering? {isLoggedIn ? <Dashboard /> : <Login />} 🔹 6. How to pass data from parent to child? <Child name="Test" /> 🔹 7. How to optimize performance? (React.memo) export default React.memo(Component); 🔹 8. What is useCallback? -> memoizes functions const handleClick = useCallback(() => {}, []); 🔹 9. What is useMemo? -> memoizes values const value = useMemo(() => compute(), []); 🔹 10. How to handle list rendering? items.map(item => <li key={item.id}>{item.name}</li>); ✅ If you are preparing for ReactJs interview, save this for your next interview! 👉 Follow Tarun Kumar for tech content, coding tips, and interview prep 🚀 #ReactJS #FrontendDeveloper #JavaScript #WebDevelopment #CodingInterview #SoftwareEngineer #TechCareers #LearnReact
To view or add a comment, sign in
-
I bombed a React interview once. Not because I didn't know the answers — but because I answered the wrong question. 🧵 The interviewer asked: "What's the difference between useCallback and useMemo?" I gave a textbook answer. Correct. Complete. Totally missed the point. The real question was: "Do you know when NOT to use them?" That one experience made me rethink how I prepare. Here's what I now know goes into a truly strong React interview — 7 concepts that actually matter in production: ───────────────────────────── 1. useCallback vs useMemo Not just what they do — but why blindly using them can hurt performance more than help. Memoization has a cost. 2. React reconciliation + the key prop The key prop isn't just for lists. Misusing it causes components to silently remount. Most devs never debug this because they don't know to look for it. 3. Closures and stale state A useEffect that captures an old value of state — and you spend 2 hours wondering why your data is always one step behind. Classic stale closure. Once you see it, you can't unsee it. 4. Shallow copy vs deep copy in state updates {...obj} feels safe. But if your object has nested arrays or objects, you're still mutating shared references. React won't re-render. The UI lies to you. 5. Preventing re-renders in large trees React.memo alone isn't enough. If your callbacks aren't stable and your context isn't split — you're still re-rendering everything. The fix is a combination, not a single tool. 6. Controlled vs uncontrolled components Choosing wrong here leads to either overengineered forms or state that React can't track. Both hurt in different ways. 7. useEffect cleanup with async calls If you don't cancel async operations on unmount, you'll set state on a component that no longer exists. AbortController is underused. Race conditions are underestimated. ───────────────────────────── 3.6 years of React has taught me that the difference between good and great frontend engineers is almost never syntax. It's knowing why something breaks — before it breaks. 💬 What's the trickiest React bug you've ever debugged? Drop it below 👇 #ReactJS #Frontend #JavaScript #WebDevelopment #SoftwareEngineering #ReactDeveloper #TechCommunity
To view or add a comment, sign in
-
💡 Frontend Interview Task: Why Your Memoization Doesn’t Work I recently saw a common React interview pattern: Optimize a component using React.memo. Sounds simple but most solutions don’t actually work. 🧪 The Task 🔹 Prevent unnecessary re-renders 🔹 Use React.memo 🔹 Keep props stable ❌ Naive approach const Child = React.memo(({ onClick }) => { console.log("render"); return <button onClick={onClick}>Click</button>; }); function App() { return <Child onClick={() => console.log("click")} />; } Looks correct… but Child still re-renders every time. 🤔 What’s happening? Every render creates a new function: () => console.log("click") From React’s perspective: 👉 props changed → re-render So React.memo does nothing. ✅ Improved approach const onClick = useCallback(() => { console.log("click"); }, []); return <Child onClick={onClick} />; Now the reference is stable → memoization works. 🧠 Key takeaways 🔹 Memoization depends on stable inputs If props change on every render, React.memo can’t help 🔹 Functions and objects are the usual problem Inline values break referential equality 🔹 React.memo is not a performance fix It only works if your data flow is already correct 🚀 Why this matters This is one of those things that looks like an optimization but often adds complexity without improving performance. In many cases, fixing state placement and re-render patterns matters more than adding memoization. Small details like this are often what differentiate mid-level and senior frontend engineers in interviews. #react #frontend #javascript #performance #webdev #softwareengineering #reactjs
To view or add a comment, sign in
-
-
Interview Questions :- Explain how this Button component works and how you would improve it for production-level use? Ans :- This component is reusable and scalable. It can be extended into a full design system by adding variants, sizes, and states like loading and disabled. //Apps.js import React, { useState } from "react"; import Button from "./Button"; function App() { return ( <div className="p-8 space-y-4"> {/* Primary Variant */} <Button variant="primary" lable="Primary" /> {/* Secondary Variant */} <Button variant="secondary" lable="Secondary" /> ); } export default App; //Button.js import React from "react"; const Button = ({ lable, variant = "primary" }) => { const variants = { primary: { backgroundColor: "#2563eb", color: "white", }, secondary: { backgroundColor: "#dc2626", color: "#1f2937", }, }; const baseStyle = { padding: "8px 16px", borderRadius: "4px", fontWeight: "600", border: "none", cursor: "pointer", opacity: 1, transition: "all 0.2s", margin: "10px", }; return ( <button onClick={() => {}} style={{ ...baseStyle, ...variants[variant] }}> {lable} </button> ); }; export default Button; 🔥 Follow Arun Dubey for more real-world interview insights #ReactJS #FrontendDeveloper #WebDevelopment #InterviewPrep #CodingTips #SoftwareEngineer
To view or add a comment, sign in
-
🚀 React Interview Question: How do you optimize React Context to reduce unnecessary re-renders? 💡 React Context is a common way to share data across components But if it’s not handled carefully, it can lead to extra re-renders, whenever the context value changes, all the components using it re-render. 🔹 1. Split your Context Don’t put everything in one place - keep contexts small and focused for better performance 🔹 2. Memoize the value Context updates are based on reference changes. - use useMemo to keep the value stable 🔹 3. Avoid inline functions New function creates a new reference, which causes a re-render - use useCallback 🔹 4. Use selector pattern Don’t consume the entire context if you only need one value 🔹 5. Keep state local when possible Not everything needs to live in Context 🔹 6. Use React.memo Helps prevent unnecessary child re-renders 🔹 Key Insight: React Context doesn’t check deep changes It only checks if the reference has changed So to optimize: - keep values stable - split contexts smartly - avoid unnecessary updates Connect/Follow Tarun Kumar for more tech content and interview prep #React #FrontendDevelopment #JavaScript #WebDev #SoftwareEngineering #CodingInterview
To view or add a comment, sign in
-
** Technical Interview Question ** Today I worked on a common but important interview question: 🔍 Find the first non-repeating element in an array 👉 Example: [4, 5, 1, 2, 0, 4] 👉 Output: 5 💡 My Approach: 1. First, I counted how many times each element appears 2. Then, I traversed the original array to find the first element that appears only once ⚡ Key Insights: Order matters — that’s why iterating over the original array is important Using a frequency map makes the solution efficient Time Complexity: O(n) Space Complexity: O(n) 🎯 Practicing these types of problems really helps in improving logic building and interview confidence, especially for Frontend / MERN Stack roles. Consistency is the key 🔥 #JavaScript #CodingInterview #ProblemSolving #MERNStack #FrontendDeveloper #ReactJS
To view or add a comment, sign in
-
-
React.js Interview Preparation Mode : Today, I stepped up the level and practiced a real interview-style problem Build a Search Filter (Debounced Input) — a common pattern asked in product-based companies. Problem Statement Create a search box that filters a list of users efficiently (avoid unnecessary re-renders & API calls). Optimized Solution (Debouncing + useEffect) import React, { useState, useEffect } from "react"; const usersData = ["Alice", "Bob", "Charlie", "David", "Eve"]; function SearchFilter() { const [search, setSearch] = useState(""); const [filtered, setFiltered] = useState(usersData); useEffect(() => { const timer = setTimeout(() => { const result = usersData.filter((user) => user.toLowerCase().includes(search.toLowerCase()) ); setFiltered(result); }, 500); // Debounce delay return () => clearTimeout(timer); }, [search]); return ( <div> <input type="text" placeholder="Search user..." value={search} onChange={(e) => setSearch(e.target.value)} /> <ul> {filtered.map((user, index) => ( <li key={index}>{user}</li> ))} </ul> </div> ); } export default SearchFilter; --- FAANG Interview Concepts Covered: - Debouncing (Performance Optimization) - useEffect Cleanup Function - Controlled Components - Efficient Rendering Follow-up Questions (Asked in Interviews): - How will you handle API-based search instead of static data? - Difference between Debouncing vs Throttling? - How to optimize this for large datasets? - How will you avoid unnecessary re-renders? Key Takeaway: In interviews, optimization matters more than just working code. Think like a product engineer, not just a coder. #ReactJS #FAANGPreparation #FrontendInterview #WebDevelopment #JavaScript #100DaysOfCode
To view or add a comment, sign in
More from this author
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