⚛️ Top 150 React Interview Questions – 37/150 📌 Topic: Importance of ‘Keys’ in Lists 🔹 WHAT is it? A Key is a special string attribute that you must include when rendering lists in React. Keys help React identify which items in an array have changed, been added, or been removed, giving each element a stable identity. 🔹 WHY is it designed this way? React uses a process called Reconciliation (Diffing) to update the UI efficiently. Performance: Instead of re-rendering every item, React uses keys to match existing elements and only move the DOM nodes that actually changed. State Preservation: Keys ensure that internal state (like text inside an input field) stays with the correct item even when the list is sorted or shuffled. Accuracy: They prevent “ghosting” bugs where data from a deleted row appears in a different row. 🔹 HOW do you do it? (The Implementation) Keys must be added to the outermost element inside the .map(). Correct Way (Using Unique IDs): function UserList({ users }) { return ( <ul> {users.map((user) => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } 🔹 WHERE are the best practices? When to Use: Always use keys whenever you render a list from an array. Use Stable IDs: Prefer unique IDs from your data (like database IDs) instead of array indexes, especially if the list can be reordered. Avoid Random Keys: Never use Math.random() as a key. It forces components to remount on every render, causing performance issues and state loss. 📝 Summary for your notes: Keys are like Roll Numbers in a classroom 🎓 Even if students change seats, the teacher (React) can still identify everyone correctly using their roll number. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions
React Keys Importance for Efficient List Rendering
More Relevant Posts
-
⚛️ Top 150 React Interview Questions – 50/150 📌 Topic: Handling Multiple Inputs 🔹 WHAT is it? Handling multiple inputs is a technique where you use one state object and one change handler to manage many form fields at once, instead of creating separate state variables for each input. This approach keeps all form data in a single place. 🔹 WHY use it? When a form has many fields (Name, Email, Phone, etc.), multiple useState hooks quickly become messy. ✅ Cleaner Code Write the logic once — it works for any number of inputs. ✅ Easy API Submission All form data is already inside one object, ready to send. ✅ Scalable Adding a new input only requires adding one key to the state object. 🔹 HOW do you implement it? Each input gets a name attribute that matches the key in state. We update the state dynamically using computed property names. const [form, setForm] = useState({ firstName: "", email: "" }); const handleChange = (e) => { const { name, value } = e.target; setForm({ ...form, [name]: value }); }; // JSX <input name="firstName" onChange={handleChange} /> <input name="email" onChange={handleChange} /> 👉 Only the field you type in gets updated. 🔹 WHERE / Best Practices ✔ Always use the spread operator (...form) → Forgetting it will overwrite other fields ✔ Ensure name attributes exactly match state keys ✔ Best suited for forms with more than 2 inputs 📝 Summary (Easy to Remember) Handling multiple inputs is like using a multi-tool 🛠️ Instead of carrying a different tool for every task (multiple states), you use one smart tool with dynamic parts (object keys). 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions #FrontendEngineer
To view or add a comment, sign in
-
-
⚛️ Top 150 React Interview Questions – 29/150 📌 Topic: useMemo vs useCallback 🔹 WHAT is the difference? The core difference is what they memoize (store): useMemo → stores the result of a function (value, object, array) useCallback → stores the function itself In short: useMemo → “Save the output” useCallback → “Save the function” 🔹 WHY do we need both? Both are used for performance optimization, but they solve different problems: Use useMemo when you want to avoid repeating an expensive calculation (e.g. sorting a large list, heavy filtering, complex math) Use useCallback when you want to avoid re-creating a function on every render, which helps prevent unnecessary re-renders of child components. 🔹 HOW do they look in code? useMemo → returns a VALUE const squaredValue = useMemo(() => { return number * number; }, [number]); useCallback → returns a FUNCTION const handleClick = useCallback(() => { console.log("Button Clicked!"); }, [dependency]); 🔹 WHERE to use which? useMemo Avoid expensive calculations Filtering, sorting, complex math When you need a stable value / object useCallback Passing functions to child components Especially with React.memo When you need a stable function reference 📝 Summary for your notes: If you need to store a Number, String, Object, or Array that takes time to compute → useMemo If you need to pass a Function to a child component and keep it stable → useCallback Think like this: useMemo → saves the answer useCallback → saves the recipe 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions
To view or add a comment, sign in
-
-
⚛️ Top 150 React Interview Questions – 77/150 📌 Topic: Sharing Logic with Hooks ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHAT is it? Sharing logic means taking common behavior (like data fetching, scroll tracking, or online status) and moving it into a Custom Hook. This allows multiple components to reuse the same logic without rewriting code. ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHY share logic using Hooks? ♻️ No Code Duplication Write the logic once and reuse it everywhere 🧠 Separation of Concerns Components focus on UI Hooks handle the “brain work” (logic) ━━━━━━━━━━━━━━━━━━━━━━ 🔹 HOW do you share logic? Create a function that starts with use and move your state and effects into it. Example: function useOnlineStatus() { const [isOnline, setIsOnline] = useState(true); // effect logic to track online/offline return isOnline; } Usage in any component: const status = useOnlineStatus(); ━━━━━━━━━━━━━━━━━━━━━━ 🔹 WHERE / Best Practices ✔ Return Logic, Not UI Custom Hooks should return data or functions, never JSX ✔ Keep Hooks Generic Design hooks for reusable tasks (example: useFetch, useForm, useLocalStorage) ━━━━━━━━━━━━━━━━━━━━━━ 📝 SUMMARY (Easy to Remember) Sharing logic with Hooks is like a plug-and-play battery 🔋 You build the power source once, and any device (component) can plug it in to start working. ━━━━━━━━━━━━━━━━━━━━━━ 👇 Comment “React” if this handbook is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #ReactHooks #CustomHooks #JavaScript #Top150ReactQuestions #LearningInPublic #Developers ━━━━━━━━━━━━━━━━━━━━━━
To view or add a comment, sign in
-
-
Everyone’s sharing the questions they faced in interviews… So here’s something different 👀 A snapshot of interview-level React & JavaScript questions — with clear answers. 🔹 Why React uses Virtual DOM? Because touching the real DOM is expensive. React diffs changes in memory first and updates only what’s needed. 🔹 Class vs Functional Components? Performance is similar. Functional components win for simplicity, hooks, and modern optimizations. 🔹 Why map() works in JSX but forEach() doesn’t? JSX needs an array to render. map() returns one. forEach() doesn’t. 🔹 What actually causes unnecessary re-renders? New object/function references, parent re-renders, and context updates. 🔹 How do you optimize large tables in React? Virtualization (render only what’s visible) + memoization. 🔹 Does React re-render mean DOM updates every time? Nope. Re-render ≠ re-paint. Virtual DOM decides what really changes. 🔹 Promise.all — what if one API fails? One failure rejects everything. Use Promise.allSettled() when partial success matters. 🔹 Best way to sync logout across multiple tabs? localStorage + storage event (simple and effective). 🔹 Where should auth tokens live on the client? Prefer HttpOnly cookies. LocalStorage is not for sensitive data. 🔹 Arrow functions vs normal functions — performance issue? Not really. The real issue is new function references on every render. 💡 Interviews don’t test what you’ve memorized — they test how well you understand the fundamentals. If you’re preparing for React / Frontend interviews, save this 📌 And if you want a part 2 (with code examples or system-design-level questions) — let me know 👇 #React #FrontendInterview #JavaScript #WebDevelopment #Performance #ReactJS #InterviewPrep 🚀
To view or add a comment, sign in
-
I once walked out of a #React interview thinking: “I know React… why did this feel so hard?” The questions weren’t tricky. They were fundamental. ❌ “Explain Virtual DOM” ❌ “Props vs State” ❌ “Why keys matter?” ❌ “useEffect dependencies?” That’s when I realized something important 👇 Most React interviews don’t test how much you’ve built — They test how clearly you understand what you already use every day. Curated with: ✅ Basic → Intermediate → Advanced questions ✅ Clear, interview-friendly explanations ✅ Real concepts interviewers care about Perfect if you’re: 🎯 Preparing for frontend/full-stack interviews 🎯 Switching companies 🎯 Revising React after long project work Because in interviews, confidence comes from clarity, not cramming. 📎 ReactJS Interview Questions PDF attached 👉 Follow Ankit Sharma Sharma for interview prep, system design, and practical engineering insights. #ReactJS #FrontendInterviews #JavaScript #WebDevelopment #SDE #InterviewPreparation
To view or add a comment, sign in
-
⚛️ Top 150 React Interview Questions — 46/150 📌 Topic: Controlled Components (Deep Dive) 🔹 WHAT is it? A Controlled Component is a form element (input, textarea, select) whose value is fully controlled by React State. Instead of the DOM managing the current value, React becomes the Single Source of Truth. 🔹 WHY is it designed this way? In normal HTML, inputs manage their own state. In React, we want full control over user input. Instant Validation Validate every keystroke (e.g., block numbers in a name field). Predictable Data Flow Since data lives in state, it’s always ready for API calls—no DOM querying. Dynamic UI Control Easily clear inputs, disable buttons, or reflect input changes live on screen. 🔹 HOW do you implement it? A Controlled Component needs two things: 1️⃣ A value prop (state → input) 2️⃣ An onChange handler (input → state) import { useState } from "react"; function MyForm() { const [name, setName] = useState(""); const handleChange = (e) => { setName(e.target.value.toUpperCase()); }; return ( <form> <input type="text" value={name} onChange={handleChange} /> <p>State value: {name}</p> </form> ); } 🔹 WHERE should you use it? Use When You need live validation, formatting, or conditional form submission. One Handler for Many Inputs Use the name attribute to handle multiple fields dynamically. Performance Tip For very large forms, consider: Uncontrolled Components (useRef) Libraries like React Hook Form 📝 Summary for your notes A Controlled Component is like a Remote-Controlled Car 🚗 The car (Input) doesn’t move on its own. Every movement is controlled by the Remote (React State) — precise and predictable. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #FormsInReact #LearningInPublic #Top150ReactQuestions
To view or add a comment, sign in
-
-
⚛️ Top 150 React Interview Questions — 49/150 📌 Topic: onChange vs. onClick 🔹 WHAT is it? These are Event Handlers in React — they tell React when to respond to user actions. onChange → Triggers whenever the value of an input changes (typing, selecting). onClick → Triggers when a user clicks or taps a button or link. 🔹 WHY are they designed this way? React needs to clearly separate data input from user actions. Real-time Tracking (onChange): Keeps React state perfectly in sync with user input (live search, character count, password strength). Action Triggering (onClick): Used for final actions like submit, delete, open modal, or send request. Fewer Bugs & Better UX: Using the right event avoids accidental actions and improves accessibility (keyboard users). 🔹 HOW do you use them? (Implementation) function SimpleSearch() { const [text, setText] = useState(""); const trackTyping = (e) => { setText(e.target.value); // onChange }; const startSearch = () => { alert("Searching for: " + text); // onClick }; return ( <> <input onChange={trackTyping} /> <button onClick={startSearch}>Go</button> </> ); } 🔹 WHERE are best practices? ✅ Use onChange for <input>, <textarea>, <select> ✅ Use onClick for buttons & actions ❌ Avoid onClick on <div> or <span> unless necessary (use <button> for accessibility) 📝 Short Summary (for notes): onChange = Mirror 🪞 Shows exactly what’s happening inside the input — live. onClick = Doorbell 🔔 Nothing happens until you press it. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #LearningInPublic #Top150ReactQuestions
To view or add a comment, sign in
-
-
🚀 React.js Interview Cheatsheet Preparing for React.js interviews or revising key concepts quickly? This cheat sheet covers the most frequently asked React topics in interviews 👇 ⚛️ Core React Basics 🔹 JSX – JavaScript syntax extension 🔹 Components – Functional & Class 🔹 Props – Immutable data passed to components 🔹 State – Mutable, component-level data 🔹 Virtual DOM – Efficient UI updates 🪝 Important React Hooks 🔹 useState() – Manage component state 🔹 useEffect() – Lifecycle & side effects 🔹 useContext() – Avoid prop drilling 🔹 useRef() – DOM access & persistent values 🔹 useMemo() / useCallback() Performance optimization 🔄 Lifecycle in Functional Components 🔹 Mount → useEffect(() => {}, []) 🔹 Update → useEffect(() => {}, [deps]) 🔹 Unmount → Cleanup function 🧭 Routing & State Management 🔹 React Router – Navigation & routing 🔹 Context API – Global state 🔹 Redux / Redux Toolkit – Large-scale apps 🧠 Performance & Best Practices 🔹 Use React.memo() to prevent re-renders 🔹 Lazy loading with React.lazy() & Suspense 🔹 Use keys properly in lists 🔹 Keep components small & reusable ❓ Popular Interview Questions ✔ State vs Props ✔ Controlled vs Uncontrolled Components ✔ Why Hooks were introduced ✔ Virtual DOM vs Real DOM ✔ CSR vs SSR #ReactJS #FrontendDeveloper #ReactInterview #JavaScript #WebDevelopment #CodingInterview #InterviewPreparation #ReactHooks #Frontend #DeveloperCommunity
To view or add a comment, sign in
-
⚛️ Top 150 React Interview Questions – 28/150 📌 Topic: The useRef Hook 🔹 WHAT is useRef? useRef is a React Hook that returns a mutable ref object. Think of it as a box that can hold any value (like a DOM element or a variable) that stays the same between re-renders. ⚠️ Most important rule: Changing a ref does NOT cause the component to re-render. 🔹 WHY do we need useRef? 1️⃣ Accessing the DOM Sometimes you need to: Focus an input field Measure the size of a div React handles most DOM work automatically, but useRef gives you a direct grab handle when needed. 2️⃣ Storing values without re-rendering useState → value change = UI re-render useRef → value change = NO UI re-render So if you want to track something (like click count) without refreshing the screen, useRef is the right tool. 🔹 HOW do you use useRef? Syntax: const myRef = useRef(initialValue); It returns an object with one property: myRef.current Example: Focusing an Input function TextInputWithFocusButton() { const inputEl = useRef(null); // 1. Create the ref const onButtonClick = () => { inputEl.current.focus(); // 3. Use 'current' }; return ( <> <input ref={inputEl} type="text" /> {/* 2. Attach the ref */} <button onClick={onButtonClick}>Focus the input</button> </> ); } 🔹 WHERE is useRef used? Managing Focus → Search bar auto-focus Media Playback → Control <video> / <audio> Third-Party Libraries → D3.js, Google Maps (need direct DOM access) Storing Previous Values → Track earlier state values 📝 Summary for your notes: useRef is like a Laser Pointer 🔦 — it lets you point directly at something on the screen (DOM). It’s also like a Secret Notebook 📒 where you store data without forcing the UI to update. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #FrontendDevelopment #ReactInterview #JavaScript #WebDevelopment #LearningInPublic #Top150ReactQuestions
To view or add a comment, sign in
-
-
⚛️ Top 150 React Interview Questions – 42/150 📌 Topic: The 3 Phases of Lifecycle 🔹 WHAT is it? Every React component follows a Lifecycle, which means it goes through specific stages from creation to removal. There are 3 main phases: Mounting → Component is created and added to the DOM Updating → Component re-renders due to props or state change Unmounting → Component is removed from the DOM 🔹 WHY is it designed this way? React uses lifecycle phases to manage timing, performance, and memory. Timing Control: Some tasks (like API calls) should run only once, not on every render. Performance: React updates the UI only when props or state actually change. Memory Safety: Unmounting gives a safe place to clean up timers, listeners, and subscriptions. 🔹 HOW do you do it? (The Implementation) In modern React, all three phases are handled using useEffect. useEffect(() => { // 1️⃣ Mounting logic console.log("Component Born (Mounting)"); const timer = setInterval(() => { console.log("Tick"); }, 1000); // 3️⃣ Unmounting logic (Cleanup) return () => { console.log("Component Dying (Unmounting)"); clearInterval(timer); }; }, [count]); // 2️⃣ Updating: runs again when 'count' changes Empty dependency [] → runs only once (Mounting) Dependency [count] → runs on update return () => {} → runs on Unmounting 🔹 WHERE are the best practices? When to Use: Mounting → API calls, subscriptions Updating → syncing data, reacting to prop/state changes Unmounting → clearing timers & event listeners Avoid Side Effects in Render: Never fetch data or run logic directly in the component body. Correct Dependencies: Wrong dependency arrays can cause infinite loops or missed updates. 📝 Summary for your notes Socho component ek Employee hai 👇 Mounting → Joining day (setup & induction) Updating → Work changes based on new instructions Unmounting → Resignation day (cleanup & handover) 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #LearningInPublic #Top150ReactQuestions
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