⚛️ 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
React useRef Hook: Accessing DOM and Storing Values
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 – 54/150 📌 Topic: useMemo vs. useCallback 🔹 WHAT is it? useMemo → Remembers a value (the answer to a heavy calculation) useCallback → Remembers a function (the way to do something) 🔹 WHY use them? useMemo Stops React from doing the same heavy work (like sorting or filtering) again and again. useCallback Stops React from re-creating functions on every render, which helps prevent unnecessary re-renders. 🔹 HOW do you use them? useMemo (The Value) const result = useMemo(() => heavyMath(data), [data]); useCallback (The Action) const handleClick = useCallback(() => doSomething(), []); 🔹 WHERE / Best Practices ✔ Use useMemo for slow or expensive calculations ✔ Use useCallback when passing functions to child components ⚠️ Rule of Thumb Don’t use them for simple things. It’s like using a safe for a candy bar 🍬 — not worth the effort. 📝 Summary (Easy to Remember) useMemo is like a Post-it note 📝 with the answer written on it. useCallback is like a video recording 🎥 showing how to do a task. 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #ReactHooks #useMemo #useCallback #Top150ReactQuestions #LearningInPublic #Developers
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 — 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 Toughest Interview Question #21 Q21: What are React Hooks, and why were they introduced? Answer: React Hooks are special functions that let you “hook into” React features like state and lifecycle methods in functional components — without writing class components. They were introduced in React 16.8 to make code more reusable, cleaner, and easier to test. Before Hooks, developers had to use class components for state or lifecycle logic, which led to bulky and repetitive code. ✨ Commonly Used Hooks: useState() → manages state in a functional component. useEffect() → handles side effects (like API calls or event listeners). useContext() → accesses context without nesting <Consumer> tags. useRef() → gets a reference to a DOM element or persists a mutable value. useMemo() & useCallback() → optimize performance by memoizing values or functions. 🔥 Why Hooks were introduced: To simplify state management inside functional components. To reuse logic easily (through custom hooks). To avoid class-based complexities (like this keyword confusion). To improve code readability and reduce boilerplate. Example: function Counter() { const [count, setCount] = useState(0); useEffect(() => { document.title = `Count: ${count}`; }, [count]); return ( <button onClick={() => setCount(count + 1)}> Clicked {count} times </button> ); } Here, useState manages the count, and useEffect updates the document title — all in a simple, functional way. 💡 In short: Hooks revolutionized React by making functional components stateful and powerful, eliminating the need for most class components. #React #ReactHooks #useState #useEffect #FrontendDevelopment #JavaScript #WebDevelopment #ReactJS #CodingInterview #TechInterview
To view or add a comment, sign in
-
⚛️ Top 150 React Interview Questions – 48/150 📌 Topic: Refs in Forms 🔹 WHAT is it? A Ref (Reference) lets you access a DOM element directly in React. In forms, instead of tracking input values with state, you use a ref to read or control the input only when needed. 👉 React State = Declarative 👉 Refs = Imperative (direct DOM access) 🔹 WHY is it designed this way? React prefers state, but sometimes direct DOM access is required. ✅ Focus Management Auto-focus an input using .focus() (login, search, OTP forms) ✅ Performance Optimization Reading values via refs does not cause re-renders — great for large forms ✅ Native DOM Control Play/pause media, trigger animations, or read values instantly 🔹 HOW do you do it? (The Implementation) Use the useRef hook in Functional Components 👇 import { useRef } from "react"; function LoginForm() { const emailRef = useRef(null); const handleLogin = () => { const email = emailRef.current.value; console.log("Email:", email); if (!email) { emailRef.current.focus(); } }; return ( <> <input ref={emailRef} placeholder="Enter email" /> <button onClick={handleLogin}>Login</button> </> ); } 🔹 WHERE are the best practices? ✔ Use refs for focus, text selection, animations, and uncontrolled forms ✔ File inputs are always uncontrolled → refs required ❌ Don’t replace state with refs everywhere ❌ Never use document.getElementById() in React — use useRef 📝 Summary for your notes A Ref is like a Laser Pointer 🔦 Instead of announcing to the whole room (state change), you point directly to the exact element (DOM) and control 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
-
-
⚛️ 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
To view or add a comment, sign in
-
-
𝗜𝗳 𝘆𝗼𝘂 𝘄𝗮𝗻𝘁 𝗯𝗲𝘁𝘁𝗲𝗿 𝗳𝗿𝗼𝗻𝘁𝗲𝗻𝗱 𝗶𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗿𝗲𝘀𝘂𝗹𝘁𝘀, 𝗽𝗿𝗲𝗽𝗮𝗿𝗲 𝗮𝗻𝘀𝘄𝗲𝗿𝘀 𝗶𝗻 𝘁𝗵𝗶𝘀 𝗳𝗼𝗿𝗺𝗮𝘁. Most candidates prepare topics. Strong candidates prepare answer structures. Here’s a simple framework you can apply to almost any JavaScript / React interview question and it works because it mirrors how interviewers think. The 4-step answer structure interviewers respond to When you’re asked any technical question, consciously follow this order: 1️⃣ 𝗦𝘁𝗮𝘁𝗲 𝘁𝗵𝗲 𝗰𝗼𝗿𝗲 𝗶𝗱𝗲𝗮 (𝟭𝟬–𝟭𝟱 𝘀𝗲𝗰𝗼𝗻𝗱𝘀) Show that you understand the concept before diving into details. Example: “Closures allow a function to retain access to its lexical scope even after the outer function has executed.” This sets confidence early. 2️⃣ 𝗘𝘅𝗽𝗹𝗮𝗶𝗻 𝘄𝗵𝘆 𝗶𝘁 𝗲𝘅𝗶𝘀𝘁𝘀 Most candidates skip this. Interviewers notice. Example: “This exists because JavaScript relies heavily on functions as first-class citizens, and without closures, async code and callbacks would be impossible to reason about.” Now you’re no longer just recalling you’re reasoning. 3️⃣ 𝗚𝗶𝘃𝗲 𝗼𝗻𝗲 𝗿𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝘂𝘀𝗲 𝗰𝗮𝘀𝗲 Not a textbook example. A real one. Example: “This is commonly used in debounced inputs, event handlers, or when preserving state inside async flows.” This bridges theory to production. 4️⃣ 𝗔𝗰𝗸𝗻𝗼𝘄𝗹𝗲𝗱𝗴𝗲 𝗼𝗻𝗲 𝗽𝗶𝘁𝗳𝗮𝗹𝗹 This is where differentiation happens. Example: “Closures can also cause memory leaks if references are unintentionally retained, especially with long-lived listeners.” Now your answer survives follow-ups. Why this works Interviewers are subconsciously checking: clarity of thought, depth, not verbosity, awareness of trade-offs.This structure hits all three. How to practice this (important) Take any interview question you know and rehearse it using only these 4 steps. If you can’t complete one step cleanly that’s your gap. No new topics needed. Just better structure This is exactly how I’ve structured the questions in Frontend Interview Blueprint: Grab eBook here: 👉 https://lnkd.in/g9hdUJkf ✅️ 300+ JavaScript & React interview questions (70% coding) ✅️ Each question pushes you to explain concept → reason → usage → pitfall ✅️ 60 system design questions (HLD + LLD) #FrontendInterview #WebDevelopment #JavaScript #ReactJS #CodingTips #FrontendEngineer #TechCareers
To view or add a comment, sign in
-
⚛️ Top 150 React Interview Questions — 45/150 📌 Topic: Why shouldComponentUpdate is Important 🔹 WHAT is it? shouldComponentUpdate() is a lifecycle method in Class Components that works like a gatekeeper. It tells React whether a component should re-render or skip rendering when new props or state arrive. It returns: true → Re-render the UI false → Skip rendering completely 🔹 WHY is it important? By default, when a parent re-renders, all child components re-render too, even if nothing actually changed. This can cause: Wasted Renders Heavy components (tables, charts, lists) re-render unnecessarily, wasting CPU and battery. Performance Bottlenecks In fast updates (typing, scrolling, resizing), skipping useless renders keeps the app smooth. Manual Control You decide which prop or state change really deserves a UI update. 🔹 HOW do you use it? You compare current vs next props/state and return a boolean. shouldComponentUpdate(nextProps, nextState) { if (this.props.id !== nextProps.id) { return true; // Re-render } return false; // Skip render } Only meaningful changes trigger rendering. 🔹 WHERE should you use it? When to Use Use it only when you notice real performance issues. Don’t add it everywhere — comparisons also cost time. Be Careful with Objects Deep comparisons can be slower than rendering itself. Modern Alternative Functional Components → React.memo() Class Components → React.PureComponent 📝 Summary for your notes shouldComponentUpdate is like a Bouncer at a Club 🚪 Instead of letting everyone in (rendering everything), the bouncer checks the Guest List (Props & State). No change? ❌ No entry (render skipped). 👇 Comment “React” if this series is helping you 🔁 Share with someone preparing for React interviews #ReactJS #ReactInterview #FrontendDevelopment #JavaScript #WebPerformance #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