Today I learned about the useRef hook and how it helps us access DOM elements and persist values without re-rendering. 🔹 What is useRef? useRef is a React Hook that returns a mutable object with a .current property. It is mainly used for: • Accessing DOM elements • Storing values without causing re-render • Keeping previous values 🔹 Accessing DOM Elements We can directly access an element using useRef. import { useRef } from "react"; function App(){ const inputRef = useRef(); const focusInput = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={focusInput}>Focus</button> </> ); } Here React gives direct access to the input element. 🔹 Storing Values Without Re-render Unlike state, updating useRef does NOT re-render the component. const countRef = useRef(0); countRef.current++; This is useful when we want to store values without updating UI. 🔹 useRef vs useState • useState → causes re-render • useRef → does NOT cause re-render 💡 Key Takeaway useRef is useful when: ✔ You need direct access to DOM ✔ You want to store values without re-render ✔ You want better performance in some cases 📌 Day 16 of my 21 Days JavaScript / React Learning Challenge #ReactJS #JavaScript #ReactHooks #FrontendDevelopment #LearningInPublic
React useRef Hook: Access DOM & Persist Values Without Re-Render
More Relevant Posts
-
How I Learned to Optimize 100k+ Items in React One day I built a simple list in React. Everything was fine… until I loaded 100,000+ items 😅 Suddenly: • UI became slow • Scrolling lagged • My laptop fan started acting like a jet engine ✈️ I thought: 👉 “React is slow.” But I was wrong. 🧠 Then I asked a better question 👉 Do users really need to see 100,000 items at once? The answer was obvious: ❌ No. Users only see what’s on the screen. 💡 That’s when it clicked Instead of rendering everything, I should render only visible items. This concept is called: 👉 Virtualization 🧠 Human version of this Imagine a long book 📖 You don’t read all pages at once. You only read the current page. Same idea. 🚀 What I changed Instead of: ❌ Rendering 100k items I did: ✅ Render only 20–30 visible items ✅ Load more as user scrolls 🔧 Tools that helped me • react-window • react-virtualized These libraries handle everything smartly. ⚡ Extra optimizations I learned • Use useMemo for heavy calculations • Use useCallback for stable functions • Avoid unnecessary re-renders • Keep components lightweight 💡 The biggest lesson Performance is not about doing more. It’s about doing less… smartly. Now whenever my app slows down, I ask: 👉 Am I rendering more than needed? Still learning React the human way. 🚀 #JavaScript #FrontendDevelopment #LearningInPublic #CleanCode #ReactJS #FrontendDevelopment #LearningInPublic #JavaScript #WebDevelopment #DeveloperJourney #ReactHook #Performance
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
-
The question that changed how I write React: "Does React need to know about this?" Early on, everything went into state. - Window width? useState + useEffect + event listener. - Theme? useState with a toggle. - Scroll position? useState on every scroll event. Every useState is a contract with React: "re-render me when this changes" Most of the time, React doesn't need that contract. Window width changes on every pixel of resize. That's hundreds of re-renders for something CSS media queries handle without JavaScript. A theme toggle? CSS custom properties. Change the variable, the browser updates everything. No React re-render needed. A scroll position for parallax? A ref + requestAnimationFrame. Direct DOM. No state. No render cycle. The instinct is "I'm in React, so I use React APIs". But React is a rendering engine. Not everything in your app is a rendering problem. The best React code I've written recently is code where React isn't involved. Event listeners instead of useEffect. CSS variables instead of useState. Refs instead of state for values React doesn't display. The fewer things React tracks, the less work it does, the faster your app feels. The best hook is the one you didn't write. #ReactJS #Frontend #SoftwareArchitecture #SystemDesign #Engineering
To view or add a comment, sign in
-
🚀 Built a Dynamic To-Do Web App using Django & JavaScript Sharing a short demo of my project where I focused on creating a smooth and interactive user experience. 🔧 Key Features: ✔️ Add, edit, and delete tasks ✔️ Inline editing without page reload ✔️ Mark tasks as completed with persistent state ✔️ Real-time UI updates using JavaScript 💡 This project helped me understand how frontend and backend work together in real-world applications. Excited to keep improving and building more! Would love your feedback 🙌 TechnoHacks EduTech Official Sandip Gavit #Django #JavaScript #FullStack #WebDevelopment #Learning
To view or add a comment, sign in
-
🧠 Just built a Trivia Question Fetcher App using HTML, CSS & JavaScript! A fun little project that fetches a brand new trivia question from an API every 5 seconds — automatically! 🎯 Here's what the app does: ✅ Fetches random trivia questions from a live API ✅ Auto-refreshes every 5 seconds with a new question ✅ Stop button to halt the question rotation ✅ Button changes color when stopped — visual feedback matters! ✅ Prevents any further API calls once stopped The biggest learning from this project? 👉 How setInterval() and clearInterval() work in JavaScript 👉 Why a simple isStopped flag can save you from unwanted API calls 👉 How to handle async fetch() responses even after a stop event #JavaScript #WebDevelopment #HTML #CSS #VanillaJS #API #100DaysOfCode #Frontend #BuildInPublic
To view or add a comment, sign in
-
There's a page in the React docs called "You Might Not Need an Effect." I'd say it's one of the most important pages in the entire React documentation. And most developers have either never read it or read it once and moved on. The whole idea comes down to one question: is your code syncing React with something React doesn't control? A WebSocket, a browser API, a third-party library? If yes, useEffect makes sense. If no, you're probably just adding extra renders and making your code harder to follow. Some patterns worth knowing: If you're deriving a value from props or state, just calculate it during render. No state, no effect needed. If you're responding to a user action like a click or form submit, put it in the event handler. The event handler already knows what happened. The effect doesn't. If you need to reset state when a prop changes, use the key prop. React will remount the component and reset everything automatically. If you're chaining effects where one sets state and triggers another, collapse all of it into a single event handler. React batches those updates into one render. If a child is fetching data just to pass it up to a parent, flip the flow. Let the parent fetch and pass it down. The rule the docs give is honestly the clearest way I've seen it put: if something runs because the user did something, it belongs in an event handler. If it runs because the component appeared on screen, it belongs in an effect. Every unnecessary useEffect is an extra render pass, an extra place for bugs to hide, and more code for the next person to untangle. Worth a read if you haven't: https://lnkd.in/gqUr7e_S How many effects in your current codebase do you think would actually pass that test? #ReactJS #Frontend #JavaScript #WebDevelopment #CleanCode
To view or add a comment, sign in
-
🚀 “I built a Todo App… to understand JavaScript — not to finish it.” Sounds simple. But this one decision changed how I see frontend development. Most people build projects to ship. I built this one to understand why things work the way they do. 👉 Here’s what clicked when I went deeper: 🧠 Every click is queued — not instant The Event Loop decides when your code runs, not you. That’s why your UI doesn’t freeze—even with multiple actions. ⚡ Search smarter, not harder Debouncing with setTimeout + clearTimeout: ✔ Fewer unnecessary executions ✔ Better performance ✔ Clear understanding of Web APIs in action 🔁 Less code, more efficiency Event Delegation changed everything: ✔ One listener instead of many ✔ Cleaner logic ✔ Scales effortlessly 📦 The moment it all made sense Microtasks vs Macrotasks: • Promises → higher priority • setTimeout → lower priority ✔ Finally understood execution order in JavaScript 🎯 What this project really taught me: ✔ Async JS isn’t magic—it’s structured ✔ The browser + JS engine work as a system ✔ Smooth UI is a result of smart scheduling 🔥 The shift most developers miss: Don’t build projects just to complete them. Build them to uncover how things actually work. 💬 If you’ve built a project that changed how you think—what was it? Let’s learn from each other 👇 #JavaScript #EventLoop #FrontendDevelopment #WebDevelopment #CodingJourney #LearnInPublic #SoftwareEngineering #AsyncJavaScript
To view or add a comment, sign in
-
🚀 Excited to share my first JavaScript Calculator project! I built this web app using HTML, CSS, and JavaScript, where you can perform basic arithmetic operations with real-time results. What started as a small learning experiment turned into a hands-on experience with: 💡 DOM manipulation 💡 Handling button clicks 💡 Building calculation logic It’s amazing how much you can learn by building something from scratch! 🎉 🎥 Check out the demo showing both the code and working app. #javascript #webdevelopment #frontend #learningbydoing #codingjourney
To view or add a comment, sign in
-
I used to build websites by writing one giant HTML file for every single page. It worked for small projects, but the more I added, the messier it got. Today, I’m documenting a much better way to build: React Components. Instead of seeing a website as one big page, I'm starting to see it as a collection of small, independent "Lego blocks." Here is what I’m practicing to keep my code organized: 1) The Lego Mindset: I build small pieces—like a button or a card—once, and then I can reuse them 1,000 times across my app. 2) JSX Power: It looks like HTML, but it lets me use actual JavaScript logic right inside my UI using curly braces. No more messy DOM manipulation. 3) Props (Communication): I learned how to pass data between these blocks. I can have one button component that changes color or text just by changing its props. The biggest lesson I learned today: "Don't Repeat Yourself" (DRY). If I need to change a design, I only have to fix it in one file, and it updates everywhere instantly. I am still learning the ropes, but building with components makes coding feel much more professional and scalable. Tomorrow, I’ll learn how to make these parts "alive" with useState! Quick question: Do you remember the first time you used React? Did the "Lego Mindset" click for you right away? #CodeWithWajid #ReactJS #WebDevelopment #30DaysOfCode #LearningToCode #BuildingInPublic #Frontend #JSX
To view or add a comment, sign in
-
🚀 #Day2 of Revising #JS 🚀 Built a Weather App using HTML, CSS & JavaScript! 🌦️ While recalling JavaScript concepts, I challenged myself to build a practical project—and ended up creating a fully functional Weather App. 🖥️ This project fetches real-time weather data and displays useful information in a clean UI. 💡 Key highlights: • Displays weather details of different cities. • Shows temperature, humidity, and overall conditions. • Integrated API for real-time data fetching. • Improved understanding of async JavaScript (fetch/Promises). This project helped me strengthen my fundamentals and gave me hands-on experience with API integration and frontend development. ✈️ Excited to build more real-world projects and to explore ! #JavaScript #WebDevelopment #FrontendDevelopment #Projects #LearningByDoing #CodingJourney 🔥
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