one concept that often comes up is refs — especially useRef and forwardRef. Let’s understand them in a simple way 👇 🔹 useRef in React useRef is a React hook that allows us to persist values between renders without causing a re-render. It is commonly used to: Access DOM elements directly Store mutable values Maintain values between renders Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const handleFocus = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleFocus}>Focus Input</button> </> ); } Here, useRef is used to directly access the input DOM element and focus it. 🔹 forwardRef in React Normally, refs cannot be passed to child functional components. forwardRef allows a parent component to pass a ref to a child component, giving access to the child’s DOM element. Example: import React, { forwardRef } from "react"; const CustomInput = forwardRef((props, ref) => { return <input ref={ref} {...props} />; }); export default CustomInput; Parent component: import { useRef } from "react"; import CustomInput from "./CustomInput"; function App() { const inputRef = useRef(); return ( <> <CustomInput ref={inputRef} /> <button onClick={() => inputRef.current.focus()}> Focus Child Input </button> </> ); } Here, the parent component can control the child input element using forwardRef. 🔹 Key Difference HookPurposeuseRefCreates a reference to store values or access DOMforwardRefAllows passing a ref from parent to child component 💡 Interview Tip: A common pattern is using forwardRef with useRef together so that parent components can interact with child DOM elements. 💬 Have you used forwardRef in real-world projects, like building reusable input or UI component libraries? #reactjs #frontenddevelopment #javascript #webdevelopment #reacthooks #interviewpreparation
React useRef and forwardRef explained
More Relevant Posts
-
“𝗛𝗼𝘄 𝗱𝗼 𝘆𝗼𝘂 𝗿𝗲𝗱𝘂𝗰𝗲 𝗯𝘂𝗻𝗱𝗹𝗲 𝘀𝗶𝘇𝗲?” One of the most common frontend interview questions — but many people answer it only from a React perspective. 𝗙𝗶𝗿𝘀𝘁, 𝘄𝗵𝘆 𝗱𝗼𝗲𝘀 𝗯𝘂𝗻𝗱𝗹𝗲 𝘀𝗶𝘇𝗲 𝗺𝗮𝘁𝘁𝗲𝗿? When a user opens your app, the browser downloads assets like HTML, CSS, and JavaScript. Out of these, JavaScript is usually the biggest performance bottleneck. A large JS bundle means: • slower initial load • more parsing/execution time • delayed interactivity • poor user experience That’s why reducing bundle size is important. 𝗛𝗼𝘄 𝘁𝗼 𝗿𝗲𝗱𝘂𝗰𝗲 𝗶𝘁? 𝟭. 𝗦𝘁𝗮𝗿𝘁 𝗯𝗲𝗳𝗼𝗿𝗲 𝗥𝗲𝗮𝗰𝘁 A lot of optimization happens at the browser / platform level: • use native image lazy loading • use Intersection Observer to load content only when it enters the viewport • avoid unnecessary API calls on component mount • use JavaScript dynamic imports to load code only when needed 𝟮. 𝗧𝗵𝗲𝗻 𝗰𝗼𝗺𝗲𝘀 𝗥𝗲𝗮𝗰𝘁 – 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 One of the best ways to reduce bundle size is code splitting — breaking one large bundle into smaller chunks so only the required code loads initially. React.lazy() is built on top of dynamic imports and helps load components only when needed instead of shipping everything in the first bundle. It can be done in 3 ways: • 𝗥𝗼𝘂𝘁𝗲-𝗯𝗮𝘀𝗲𝗱 → load pages only when user visits them • 𝗖𝗼𝗺𝗽𝗼𝗻𝗲𝗻𝘁-𝗯𝗮𝘀𝗲𝗱 → lazy load heavy components like charts, maps, editors, modals • 𝗠𝗼𝗱𝘂𝗹𝗲-𝗯𝗮𝘀𝗲𝗱 → load heavy libraries/modules only when required 𝟰. 𝗗𝗼𝗻’𝘁 𝘀𝘁𝗼𝗽 𝗮𝘁 𝗹𝗮𝘇𝘆 𝗹𝗼𝗮𝗱𝗶𝗻𝗴 Real-world bundle optimization also includes: • removing unused dependencies • importing only what you use • tree shaking • minification • gzip / brotli compression Best way to think about it: Instead of asking: “How do I optimize React?” Ask: “Does the user really need this code on initial load?” That mindset alone can save a lot of bundle size. #frontend #react #javascript #webperformance #webdevelopment #codeSplitting #bundleoptimization #interviewprep
To view or add a comment, sign in
-
Understanding why a component re-renders in React, even when it seems nothing has changed, is crucial for optimizing performance. In the example of the Parent component, we have: ```javascript function Parent() { const [count, setCount] = useState(0); const handleClick = () => { console.log("Clicked"); }; return <Child onClick={handleClick} />; } ``` Even when the Child component is wrapped with React.memo, it still re-renders. The reason is that functions in JavaScript are re-created on every render. Therefore, on each render, `handleClick` is not equal to the previous `handleClick`, leading React to perceive it as a new prop. As a result, the Child component receives a new function reference, prompting React to think the props have changed, which causes the Child to re-render. To prevent this, we can use `useCallback` to memoize the function: ```javascript const handleClick = useCallback(() => { console.log("Clicked"); }, []); ``` This way, React retains the same function reference between renders. Key Insight: React compares references, not function logic. However, it's important to note that `useCallback` should not be overused. It is best utilized when: - Passing functions to child components - Optimizing performance with React.memo #ReactJS #JavaScript #FrontendDevelopment #WebDevelopment #SoftwareEngineering #CodingJourney #LearninglnPublic #DeveloperLife #ReactInternals #FrontendEngineer #TechInterview #StateManagement #ReactHooks
To view or add a comment, sign in
-
𝐓𝐡𝐢𝐧𝐤𝐢𝐧𝐠 `React.memo` 𝐦𝐚𝐤𝐞𝐬 𝐲𝐨𝐮𝐫 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬 𝐩𝐞𝐫𝐟𝐞𝐜𝐭𝐥𝐲 𝐩𝐞𝐫𝐟𝐨𝐫𝐦𝐚𝐧𝐭? 𝐓𝐡𝐢𝐧𝐤 𝐚𝐠𝐚𝐢𝐧. Many of us reach for `React.memo` to prevent unnecessary re-renders in child components. And it works wonders... most of the time. But here's the catch: `React.memo` performs a shallow comparison of props. If you're passing object, array, or function props, even if their internal values haven't changed, a new reference is created on every parent re-render. This new reference makes `React.memo` think the prop has changed, leading to an unwanted re-render of your memoized child component. ```javascript // Parent component re-renders: const data = { id: 1, name: 'Item' }; // New object reference! <MemoizedChild item={data} /> // Or with a function: const handleClick = () => console.log('clicked'); // New function reference! <MemoizedChild onClick={handleClick} /> ``` The solution? Pair `React.memo` with `useCallback` for functions and `useMemo` for objects/arrays. ```javascript // In Parent component: const memoizedData = useMemo(() => ({ id: 1, name: 'Item' }), []); const memoizedHandleClick = useCallback(() => console.log('clicked'), []); <MemoizedChild item={memoizedData} onClick={memoizedHandleClick} /> ``` This ensures your props maintain the same reference across renders, allowing `React.memo` to truly shine. It's a small detail, but crucial for optimizing complex applications. How aggressively do you memoize in your React apps? Share your go-to strategies! #React #ReactJS #FrontendDevelopment #WebPerformance #JavaScript
To view or add a comment, sign in
-
🚀 Project Update: React Card UI A simple card project built using React.js to show user details in a clean way. 🔗 GitHub Link: https://lnkd.in/gi56aNdJ ✨ Features: ✔ Show data using map() ✔ Clean and simple design ✔ Light and dark theme ⚙ Tech Stack: React.js | JavaScript | HTML | CSS This project helped improve basic React skills and understanding of UI. More projects coming soon. #ReactJS #FrontendDeveloper #WebDevelopment #JavaScript #Projects
To view or add a comment, sign in
-
🚨 React vs Vanilla JavaScript: the showdown that could save you weeks of work A: React – a component library that handles UI state, routing and ecosystem tools. It shines for large SPAs, offers reusable pieces and has a massive community. B: Vanilla JavaScript – pure browser language, no extra libraries, runs everywhere and lets you keep payload tiny. My verdict: Vanilla JavaScript wins for most client sites. In the past nine years I’ve built dozens of marketing pages, e‑commerce fronts and dashboards. When the page needs a simple form, a carousel or a dynamic headline, a few lines of native code load instantly and avoid the bundle size of a React build. I only reach for React when the product truly behaves like a single page app with complex state, multiple views and a dedicated development team. ✅ Your turn. A or B? Drop it in the comments. 💡 Check if your next project is overengineered. #ThisOrThat #WebDevelopment #WebDesign #Poll #TechDebate #Developer #JavaScript #ReactJS #Frontend #Coding #Performance #UX #WebPerformance #NoCode #Programming
To view or add a comment, sign in
-
🚀 Understanding Lists & Keys in React — Simplified! Rendering lists in React is easy… 👉 But doing it correctly is what most developers miss. 💡 What are Lists in React? Lists allow you to render multiple elements dynamically using arrays. const items = ["Apple", "Banana", "Mango"]; items.map((item) => <li>{item}</li>); 💡 What are Keys? 👉 Keys are unique identifiers for elements in a list items.map((item) => <li key={item}>{item}</li>); 👉 They help React track changes efficiently ⚙️ How it works When a list updates: 👉 React compares old vs new list 👉 Keys help identify: Added items Removed items Updated items 👉 This process is part of Reconciliation 🧠 Why Keys Matter Without keys: ❌ React may re-render entire list ❌ Performance issues ❌ Unexpected UI bugs With keys: ✅ Efficient updates ✅ Better performance ✅ Stable UI behavior 🔥 Best Practices (Most developers miss this!) ✅ Always use unique & stable keys ✅ Prefer IDs from data (best choice) ❌ Avoid using index as key (in dynamic lists) ⚠️ Common Mistake // ❌ Using index as key items.map((item, index) => <li key={index}>{item}</li>); 👉 Can break UI when items reorder 💬 Pro Insight Keys are not for styling or display— 👉 They are for React’s internal diffing algorithm 📌 Save this post & follow for more deep frontend insights! 📅 Day 11/100 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactInternals #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
REACT INTERNALS - PART 10 How React Prioritizes Updates (Concurrent Rendering) In Part 9, we saw: • React batches multiple updates • Executes them in a single render Now the next question is: What if some updates are more important than others? 🔥 The Problem Not all updates should be treated equally. Example: • Typing in an input → urgent • Rendering a large list → heavy work If React processes both together: The UI can feel slow and unresponsive 🧩 Example function App() { const [input, setInput] = React.useState("") const [list, setList] = React.useState([]) const handleChange = (e) => { setInput(e.target.value) // urgent setList(generateBigList()) // heavy work } return <input onChange={handleChange} /> } ⚠️ Without Prioritization • Input update waits for heavy work • Typing feels slow • Poor user experience 🧠 Why This Happens React needs a way to handle updates with different importance 🧠 React’s Solution React introduces Concurrent Rendering to handle this It allows React to: • Prioritize important updates • Run less important work later 🔧 Using startTransition const [isPending, startTransition] = React.useTransition() const handleChange = (e) => { setInput(e.target.value) // high priority startTransition(() => { setList(generateBigList()) // low priority }) } 🔍 What Happens Now? • Input updates immediately • Heavy work runs later • UI stays responsive 🧠 What is Concurrent Rendering? Concurrent rendering means: React can pause, resume, or delay rendering work Instead of blocking the UI ⚠️ Important Clarification React is NOT truly parallel or multi-threaded • It does NOT run updates at the same time • It breaks work into small units • And schedules them intelligently 🎯 Key Insight React prioritizes urgent updates and runs less important work later 🔑 Final Takeaway Concurrent rendering keeps the UI responsive by scheduling updates based on priority Next: How React Fiber makes this possible internally #ReactJS #FrontendDevelopment #JavaScript #ReactInternals #SoftwareEngineering
To view or add a comment, sign in
-
-
The DOM is officially a bottleneck. 🤯 Cheng Lou (former React core team) just dropped Pretext, and it is challenging how browsers have handled text layout for the past 30 years. For decades, figuring out how much space a paragraph occupies meant rendering it in the browser and measuring it. This triggers layout reflows (using tools like getBoundingClientRect), which is one of the most expensive and thread-blocking operations in web development. Enter Pretext: A pure JavaScript/TypeScript library that handles multiline text measurement without touching the DOM. Here is why it is so powerful: Instead of relying on CSS rendering, it uses an off-screen Canvas and a clever two-phase API (prepare() and layout()) to pre-calculate word sizes using pure arithmetic. The layout operations run in roughly 0.09ms. It natively supports platform-specific emojis, complex text directions (RTL), and different languages. It enables previously impossible UI effects, like text fluidly wrapping around moving, draggable obstacles in real-time. The project rocketed past 10,000 GitHub stars in just days because it solves a massive performance hurdle for the next generation of spatial and interactive UIs. #WebDevelopment #JavaScript #TypeScript #Frontend #SoftwareEngineering #TechNews #UIUX
To view or add a comment, sign in
-
🚀 Built a To-Do App using HTML, CSS & JavaScript(basic) ✨ Features: ✔ Add tasks dynamically ✔ Delete tasks with one click ❌ ✔ Clean and simple UI 🧠 Key Learnings: * DOM manipulation * Event handling * Improving logic building Excited to build more real-world projects and grow as a developer 🚀 #WebDevelopment #Frontend #Projects #Learning
To view or add a comment, sign in
-
𝐑𝐞𝐚𝐜𝐭 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐕𝐢𝐞𝐰 𝐓𝐫𝐚𝐩: How do you write an Error Boundary using functional components? 🚨🏴☠️ If your answer is, "I’ll just use a try/catch inside a useEffect," you might be costing yourself the offer. Here is a quick refresher on Error Boundaries and the production-level tip you need to ace this question. 🧠 𝐓𝐡𝐞 𝐂𝐨𝐫𝐞 𝐂𝐨𝐧𝐜𝐞𝐩𝐭 Since React 16, a single unhandled error in a component during rendering will unmount the entire component tree—resulting in the dreaded blank white screen. Error Boundaries act like a massive catch {} block for your UI. If a localized component (like a product review widget) crashes, the boundary catches it, prevents the rest of the page from unmounting, and displays a graceful fallback UI instead. 📌 𝐈𝐧𝐭𝐞𝐫𝐯𝐢𝐞𝐰 𝐓𝐢𝐩 Interviewers love asking how to build one in modern, functional React. The catch? You can't. Native React still requires a Class Component using componentDidCatch or static getDerivedStateFromError to build a boundary from scratch. There are no hook equivalents yet. 💻 𝐏𝐫𝐨𝐝𝐮𝐜𝐭𝐢𝐨𝐧 𝐀𝐩𝐩 𝐮𝐬𝐞 𝐜𝐚𝐬𝐞 If you want to show senior-level thinking, explain that while you can write a custom class wrapper, the industry standard for production apps is using Brian Vaughn’s react-error-boundary library. Why? It gives you two massive advantages: 1. 𝘾𝙡𝙚𝙖𝙣 𝙁𝙪𝙣𝙘𝙩𝙞𝙤𝙣𝙖𝙡 𝙒𝙧𝙖𝙥𝙥𝙚𝙧𝙨: You get a <ErrorBoundary> component that accepts a simple fallback UI and an onReset function to easily clear caches and let the user "try again." 2. 𝘾𝙖𝙩𝙘𝙝𝙞𝙣𝙜 𝙩𝙝𝙚 𝙪𝙣𝙘𝙖𝙩𝙘𝙝𝙖𝙗𝙡𝙚: Native error boundaries cannot catch errors inside async API calls or event handlers (like an onClick). The library provides a useErrorBoundary hook that allows you to manually push async errors into the boundary, triggering your fallback UI perfectly. Stop letting a single broken widget crash your entire application! #ReactJS #WebDevelopment #Frontend #SoftwareEngineering #TechInterviews #JavaScript
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