🚀 Understanding useRef in React — Simplified! Not all data in React should trigger a re-render. 👉 That’s where useRef becomes powerful. 💡 What is useRef? useRef is a hook that lets you store a mutable value that persists across renders—without causing re-renders. ⚙️ Basic Syntax const ref = useRef(initialValue); 👉 Access value using: ref.current 🧠 How it works Value persists across renders Updating it does NOT trigger re-render Works like a mutable container 🔹 Example const countRef = useRef(0); const handleClick = () => { countRef.current += 1; console.log(countRef.current); }; 👉 UI won’t update—but value persists 🧩 Real-world use cases ✔ Accessing DOM elements (focus, scroll) ✔ Storing previous values ✔ Managing timers / intervals ✔ Avoiding unnecessary re-renders 🔥 Best Practices (Most developers miss this!) ✅ Use useRef for non-UI data ✅ Use it for DOM access ✅ Combine with useEffect when needed ❌ Don’t use useRef for UI state ❌ Don’t expect UI updates from it ⚠️ Common Mistake // ❌ Expecting UI update countRef.current += 1; 👉 React won’t re-render 💬 Pro Insight 👉 useRef = Persist value without re-render 👉 useState = Persist value with re-render 📌 Save this post & follow for more deep frontend insights! 📅 Day 14/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #useRef #WebDevelopment #SoftwareEngineering #100DaysOfCode 🚀
React useRef Explained: Persistent Value Without Re-Render
More Relevant Posts
-
⚛️ 𝗜𝗺𝗽𝗿𝗼𝘃𝗶𝗻𝗴 𝗥𝗲𝗮𝗰𝘁 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 — 𝗨𝘀𝗶𝗻𝗴 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 As React applications grow, bundle size increases — which directly impacts initial load time. Common problem: • large JS bundle • slow first load • unnecessary code loaded upfront A better production approach is 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴. ❌ 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 𝘪𝘮𝘱𝘰𝘳𝘵 𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 𝘧𝘳𝘰𝘮 "./𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥"; 𝘪𝘮𝘱𝘰𝘳𝘵 𝘙𝘦𝘱𝘰𝘳𝘵𝘴 𝘧𝘳𝘰𝘮 "./𝘙𝘦𝘱𝘰𝘳𝘵𝘴"; 𝘪𝘮𝘱𝘰𝘳𝘵 𝘚𝘦𝘵𝘵𝘪𝘯𝘨𝘴 𝘧𝘳𝘰𝘮 "./𝘚𝘦𝘵𝘵𝘪𝘯𝘨𝘴"; All components load upfront — even if not used immediately. ❌ 𝗪𝗶𝘁𝗵𝗼𝘂𝘁 𝗖𝗼𝗱𝗲 𝗦𝗽𝗹𝗶𝘁𝘁𝗶𝗻𝗴 𝘪𝘮𝘱𝘰𝘳𝘵 { 𝘭𝘢𝘻𝘺, 𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦 } 𝘧𝘳𝘰𝘮 "𝘳𝘦𝘢𝘤𝘵"; 𝘤𝘰𝘯𝘴𝘵 𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 = 𝘭𝘢𝘻𝘺(() => 𝘪𝘮𝘱𝘰𝘳𝘵("./𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥")); 𝘤𝘰𝘯𝘴𝘵 𝘙𝘦𝘱𝘰𝘳𝘵𝘴 = 𝘭𝘢𝘻𝘺(() => 𝘪𝘮𝘱𝘰𝘳𝘵("./𝘙𝘦𝘱𝘰𝘳𝘵𝘴")); 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘈𝘱𝘱() { 𝘳𝘦𝘵𝘶𝘳𝘯 ( <𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦 𝘧𝘢𝘭𝘭𝘣𝘢𝘤𝘬={<𝘱>𝘓𝘰𝘢𝘥𝘪𝘯𝘨...</𝘱>}> <𝘋𝘢𝘴𝘩𝘣𝘰𝘢𝘳𝘥 /> <𝘙𝘦𝘱𝘰𝘳𝘵𝘴 /> </𝘚𝘶𝘴𝘱𝘦𝘯𝘴𝘦> ); } Now components load 𝗼𝗻𝗹𝘆 𝘄𝗵𝗲𝗻 𝗻𝗲𝗲𝗱𝗲𝗱. 📌 Where this helps most: • large dashboards • admin panels • multi-page apps • heavy third-party libraries 📌 𝗣𝗿𝗼𝗱𝘂𝗰𝘁𝗶𝗼𝗻 𝗕𝗲𝗻𝗲𝗳𝗶𝘁𝘀: • faster initial load • reduced bundle size • better performance • improved user experience 📌 𝗕𝗲𝘀𝘁 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗲𝘀: • split at route level • avoid over-splitting • use meaningful fallbacks • monitor bundle size Loading everything at once works — but splitting wisely improves performance significantly. 💬 Curious — do you apply code splitting at route level or component level? #ReactJS #CodeSplitting #Performance #FrontendDevelopment #JavaScript #WebDevelopment #SoftwareEngineering #Optimization
To view or add a comment, sign in
-
🚫 Can we use useState without re-render in React? Short answer: No. You can’t. 🧠 Why? useState is designed to: 👉 Update data 👉 Trigger re-render const [count, setCount] = useState(0); setCount(1); // ✅ Always causes re-render There’s no way to “silently” update state. ⚠️ Common misconception “Use useState but avoid re-render like useRef” 👉 That’s not possible — it goes against how React works. 💡 What should you do instead? If your goal is: ✅ Store value without re-render Use useRef const countRef = useRef(0); countRef.current += 1; // ❌ No re-render ✅ Reduce unnecessary re-renders (not eliminate) ✔ Update only when value changes if (value !== newValue) { setValue(newValue); } ✔ Split components (localize state) ✔ Use React.memo for child components ✔ Use useMemo / useCallback for stability 🔥 Key takeaway useState → triggers re-render ✅ useRef → no re-render ❌ You choose based on UI vs non-UI data 💡 Rule of thumb: If UI should update → useState If UI should NOT update → useRef #ReactJS #Frontend #JavaScript #ReactHooks #WebDevelopment #InterviewPrep
To view or add a comment, sign in
-
🚀 useDeferredValue in React — Smooth UI Without Blocking Ever noticed this? 👉 Typing feels laggy when filtering large data 👉 UI freezes during heavy updates You fixed it with useTransition… Now meet its smarter sibling 👉 useDeferredValue 💡 What is useDeferredValue? useDeferredValue lets you: 👉 Delay updating a value 👉 Keep UI responsive 👉 Let React handle prioritization ⚙️ Basic Syntax const deferredValue = useDeferredValue(value); 👉 React delays updating this value 👉 Until higher priority work is done 🧠 How it works const [query, setQuery] = useState(""); const deferredQuery = useDeferredValue(query); const filteredData = useMemo(() => { return expensiveFilter(data, deferredQuery); }, [deferredQuery]); 👉 Typing stays fast 👉 Filtering happens in background 🧩 Real-world Example Search input: ❌ Without useDeferredValue: Every keystroke triggers heavy filtering UI becomes slow ✅ With useDeferredValue: Input stays smooth Results update slightly later 🔥 Key Difference vs useTransition 👉 useTransition → delays state update 👉 useDeferredValue → delays value usage ⚠️ Common Mistake // ❌ Using for simple values const value = useDeferredValue(count); 👉 Not needed for cheap operations 🔥 Best Practices ✅ Use with expensive computations ✅ Combine with useMemo ✅ Ideal for search/filter UI ❌ Don’t use everywhere blindly 💬 Pro Insight (Senior-Level Thinking) 👉 useDeferredValue improves: ✔ Perceived performance ✔ User experience 👉 Not actual speed—but responsiveness 📌 Save this post & follow for more deep frontend insights! 📅 Day 26/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #ConcurrentRendering #PerformanceOptimization #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
🚀 Understanding Event Handling in React — Simplified! In React, user interactions drive everything. 👉 Clicking a button 👉 Typing in input 👉 Submitting a form All of this is handled through events. 💡 What is Event Handling in React? Event handling allows you to respond to user actions using functions. <button onClick={handleClick}>Click Me</button> 👉 When clicked → handleClick runs ⚙️ How it works function App() { const handleClick = () => { console.log("Button clicked!"); }; return <button onClick={handleClick}>Click</button>; } ✅ Pass function reference (not function call) ✅ React handles binding automatically 🧠 Key Differences from HTML 🔹 HTML: <button onclick="handleClick()">Click</button> 🔹 React: <button onClick={handleClick}>Click</button> 👉 CamelCase events 👉 Pass functions, not strings 🧩 Common Events in React ✔ onClick → Button click ✔ onChange → Input change ✔ onSubmit → Form submit ✔ onMouseEnter / onMouseLeave ✔ onKeyDown / onKeyUp 🔥 Best Practices (Most developers miss this!) ✅ Always pass function reference ✅ Use arrow functions when needed ✅ Keep handlers clean and reusable ❌ Don’t call function directly in JSX ⚠️ Common Mistake // ❌ Wrong <button onClick={handleClick()}> 👉 This runs immediately instead of on click 💬 Pro Insight React uses a Synthetic Event system: 👉 Normalizes events across all browsers 👉 Improves performance and consistency 📌 Save this post & follow for more deep frontend insights! 📅 Day 9/100 #ReactJS #FrontendDevelopment #JavaScript #WebDevelopment #ReactHooks #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
Hook: We need to talk about the awkward phase between useState and installing Redux. For a long time, I defaulted to useState for literally everything. Then you hit a feature—like a complex multi-step form or a data-heavy dashboard—and suddenly your component has six different state setters. Your event handlers turn into a tangled mess of setLoading(false), setData(res), and setError(null), all firing at once and risking race conditions. That’s exactly when useReducer goes from being "that confusing React hook" to the most vital tool for clean architecture. ✅ When you SHOULD use it: Dependent State: When updating one piece of state requires changing another at the exact same time (e.g., resolving an API call updates loading, data, and error simultaneously). Complex Objects: When your state is a deeply nested object or array that requires precise mapping or filtering on every update. Centralizing Logic: When you want to pull messy update logic out of your UI component and into a pure, highly testable JavaScript function. You can unit-test a reducer without ever touching a React component. ❌ When you SHOULD NOT use it: Simple Primitives: Please don't write a 15-line reducer with action types and switch statements just to toggle a modal open and closed. useState is perfectly fine for isolated, flat values. Just to look "advanced": The boilerplate is real. If the state is simple, keep the code simple. Don't frustrate the next developer who reads your code just to flex a hook. 💡 Why it matters in production: At the product-company level, you don't always need Redux, Zustand, or MobX for every feature. Pairing useReducer with the Context API gives you a powerful, localized global state. You can pass the dispatch function down the tree, completely avoiding prop-drilling without bloating your bundle size with third-party dependencies. It takes a minute to shift your brain from "updating values" to "dispatching actions," but your future self (and your teammates) will thank you when debugging. What is your personal threshold for making the switch from useState to useReducer? Let's debate below. #ReactJS #FrontendEngineering #SoftwareArchitecture #CleanCode #JavaScript
To view or add a comment, sign in
-
-
Everything inside your component is recreated on every render. Most developers know this. But very few actually feel the impact of it. I didn’t… until it started affecting performance in a real feature. When React re-renders a component, it doesn’t “update” it. It runs the entire function again. That means: • Variables are re-created • Functions get new references • Objects & arrays become new instances Even if the UI looks exactly the same. At first, this feels harmless. Until you see something like this 👇 A small state change in parent → Triggers multiple child re-renders → No visible bug → but UI becomes slower The problem wasn’t React. It was this: const data = { value: count }; const handleClick = () => doSomething(); Looks fine. But on every render: - data is a new object - handleClick is a new function And React sees: “New reference = something changed” The real issue is not re-rendering. It’s uncontrolled identity changes. That’s when these stopped being “optimizations” for me: • React.memo • useCallback • useMemo And became tools to control behavior. The shift that matters: Don’t ask: Why did it re-render? Ask: What changed by reference? Once you understand this, you stop writing React casually. And start writing it intentionally. Curious — what’s one time React rendering surprised you? #ReactJS #Frontend #JavaScript #WebDevelopment #SoftwareEngineering #DevLife
To view or add a comment, sign in
-
-
🚀 Built a Contact Dashboard using HTML, CSS & JavaScript! Excited to share my latest mini project — a Contact Dashboard that combines a form and a to-do list in one clean interface. ✨ Features: ✔️ Contact Form with validation ✔️ Dynamic To-Do List ✔️ Clean and responsive UI This project helped me strengthen my fundamentals in DOM manipulation and frontend structuring. Next step: Adding Local Storage & backend integration 🔥 Would love your feedback! 🙌 link : https://lnkd.in/g8EaZGia #WebDevelopment #FrontendDeveloper #JavaScript #HTML #CSS #Projects #LearningByDoing
To view or add a comment, sign in
-
localStorage vs sessionStorage in JavaScript frontend Both are used to store data in the browser, but choosing the right one is important for application behavior localStorage Data persists even after closing the browser Shared across all tabs of the same origin Best suited for long term data like user preferences sessionStorage Data exists only for the duration of the tab session Cleared when the tab is closed Isolated per tab Best suited for temporary data like session state Key difference comes down to data lifecycle and scope localStorage for persistence sessionStorage for session based isolation Using the wrong storage can lead to unexpected user experience issues Frontend decisions are not just UI level They directly impact how users interact with your application #javascript #frontend #performance
To view or add a comment, sign in
-
🚀 Custom Hooks in React — Write Once, Reuse Everywhere As your React app grows… 👉 Logic starts repeating 👉 Components become messy 👉 Code becomes harder to maintain That’s where Custom Hooks come in. 💡 What are Custom Hooks? Custom Hooks are reusable functions that let you extract and share logic between components. 👉 Just like built-in hooks—but created by you ⚙️ Basic Example function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount(c => c + 1); return { count, increment }; } 👉 Use it anywhere: const { count, increment } = useCounter(); 🧠 How it works ✔ Uses existing hooks (useState, useEffect, etc.) ✔ Encapsulates logic ✔ Returns reusable values/functions 🧩 Real-world use cases ✔ API fetching logic (useFetch) ✔ Form handling (useForm) ✔ Debouncing inputs (useDebounce) ✔ Authentication logic (useAuth) 🔥 Why Custom Hooks Matter 👉 Without them: ❌ Duplicate logic across components ❌ Hard to maintain code 👉 With them: ✅ Clean components ✅ Reusable logic ✅ Better scalability 🔥 Best Practices (Most developers miss this!) ✅ Prefix with “use” (important for React rules) ✅ Keep hooks focused on one responsibility ✅ Avoid tightly coupling with UI ❌ Don’t over-abstract too early ⚠️ Common Mistake // ❌ Mixing UI + logic function useData() { return <div>Data</div>; } 👉 Hooks should return data/logic—not JSX 💬 Pro Insight (Senior Thinking) 👉 Components = UI 👉 Hooks = Logic 👉 Clean separation = scalable architecture 📌 Save this post & follow for more deep frontend insights! 📅 Day 18/100 #ReactJS #FrontendDevelopment #JavaScript #ReactHooks #CodeQuality #SoftwareEngineering #100DaysOfCode 🚀
To view or add a comment, sign in
-
-
React Folder Structure That Scales 🚀 Most beginners start like this: src/ ├── Home.jsx ├── Navbar.jsx ├── Login.jsx ├── api.js ├── redux.js It works at first. But after adding authentication, APIs, Redux, hooks, layouts, and 20+ pages, finding a file becomes frustrating. That’s why folder structure matters. src/ ├── api/ ├── assets/ ├── components/ │ ├── common/ │ ├── forms/ │ └── ui/ ├── config/ ├── context/ ├── features/ │ ├── auth/ │ ├── dashboard/ │ ├── profile/ │ └── products/ ├── hooks/ ├── layout/ ├── pages/ ├── redux/ ├── routes/ ├── services/ ├── utils/ ├── .env ├── .env.development ├── .env.production └── App.jsx Why this structure? • components/→ Reusable UI • pages/→ Full screens • api/ & services/→ API logic • redux/ → Global state • hooks/ → Reusable logic • routes/ → Clean routing • features/ → Keep each module together For large apps, I prefer feature-based architecture: features/ └── auth/ ├── components/ ├── pages/ ├── hooks/ ├── services/ └── authSlice.js This keeps auth-related files in one place instead of searching through 5 different folders. Best rule: • Small project → Simple structure • Medium project → Organized folders • Large project → Feature-based architecture Clean folder structure = easier debugging + faster development + better teamwork. How do you organize your React projects? #react #reactjs #frontend #webdevelopment #javascript #redux #vite
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