Today I learned about the useRef Hook in React and how to use localStorage to manage data in the browser. ** useRef Hook The useRef hook is used to create a reference that persists across renders. It is commonly used to directly access DOM elements or store values without causing re-renders. Example: import { useRef } from "react"; function InputFocus() { const inputRef = useRef(null); const handleClick = () => { inputRef.current.focus(); }; return ( <> <input ref={inputRef} /> <button onClick={handleClick}>Focus Input</button> </> ); } ** localStorage in JavaScript localStorage allows us to store data in the browser so that it remains even after refreshing the page. • setItem() – Store data • getItem() – Retrieve data • update – Modify existing data • removeItem() – Delete data Example: localStorage.setItem("name", "Avesh"); const data = localStorage.getItem("name"); localStorage.removeItem("name"); @Sheryians Coding School @Sarthak Sharma @Daneshwar Verma @Devendra Dhote @Ritik Rajput #ReactJS #JavaScript #FullStackDeveloper #WebDevelopment #CodingJourney
React useRef Hook & localStorage for Persistent Data Storage
More Relevant Posts
-
🚀 Day 17/30 – Custom Hooks (Deep Dive) Tired of repeating the same logic in multiple components? 🤔 Today I learned how to make React code reusable & clean ⚡ 👉 Custom Hooks Today I learned: ✅ Custom Hooks are reusable functions using React Hooks ✅ They help extract and reuse logic across components ✅ Must always start with "use" (naming convention) --- 💻 Problem: Same logic repeated in multiple components ❌ (e.g. fetching data, form handling) --- 💻 Solution: Create a custom hook ✅ --- 💻 Example: function useCounter() { const [count, setCount] = useState(0); const increment = () => setCount((prev) => prev + 1); const decrement = () => setCount((prev) => prev - 1); return { count, increment, decrement }; } function App() { const { count, increment, decrement } = useCounter(); return ( <> <h2>{count}</h2> <button onClick={increment}>+</button> <button onClick={decrement}>-</button> </> ); } --- 🔥 What actually happens: 1️⃣ Logic is written once inside custom hook 2️⃣ Any component can reuse it 3️⃣ Each component gets its own state --- 💡 Real Use Cases: - API fetching (useFetch) - Form handling (useForm) - Authentication logic - Debouncing input --- ⚡ Advanced Insight: Custom Hooks don’t share state ❌ 👉 They share logic, not data --- 🔥 Key Takeaway: Write logic once → reuse everywhere. Are you still repeating logic or using custom hooks? 👇 #React #CustomHooks #FrontendDevelopment #JavaScript #CleanCode
To view or add a comment, sign in
-
-
#111DaysOfLearningForChange Day 5: Today I implemented infinite scrolling in vanilla js using IntersectionObserver Object(API). #111DaysOfLearningForChange #CodeCodeCode for Change #MERN #React #frontend 🍀 js snippet: let i = 1; const parent = document.querySelector('.parent'); const footer = document.querySelector('.footer'); const observer = new IntersectionObserver( (entries) => { entries.forEach((entry) => { if (entry.isIntersecting) { footer.innerHTML = 'You saw meee'; } if (entry.intersectionRatio > 0.1) { entry.target.innerHTML += '<br>you saw 10% of me'; } if (entry.intersectionRatio > 0.5) { entry.target.innerHTML += '<br>you saw half of me'; } if (entry.intersectionRatio > 0.8) { entry.target.innerHTML = "<br>Keep going and <br>you won't see me"; } if (entry.intersectionRatio > 0.9) { entry.target.style.height = '20vh'; } if (entry.intersectionRatio == 1) { parent.innerHTML += `<div class="box">This is new Box - ${i++}</div>`; if (i > 25) { parent.innerHTML += `<div class="stop">Ok That's enough Scrolling</div>`; footer.remove(); } } }); }, { threshold: [0, 0.1, 0.5, 0.8, 0.9, 1], } ); observer.observe(document.querySelector('.footer'));
To view or add a comment, sign in
-
🧠 Memory Management in JavaScript — What Every Developer Should Know Memory management is something many JavaScript developers ignore… until performance issues start appearing 🚨 Let’s break it down 👇 🔹 How JavaScript Stores Data JavaScript uses two types of memory: 👉 Stack (Primitive Data Types) Stored directly in memory (fast & simple) Examples: • number • string • boolean • null • undefined • bigint • symbol Example: let a = 10; let b = a; // copy of value 👉 Each variable gets its own copy ✅ 👉 Heap (Reference Data Types) Stored as references (complex structures) Examples: • objects • arrays • functions Example: let obj1 = { name: "Kiran" }; let obj2 = obj1; obj2.name = "JS"; console.log(obj1.name); // "JS" 👉 Both variables point to the same memory location ❗ 🔹 Garbage Collection (GC) JavaScript uses “Mark and Sweep”: Marks reachable data Removes unreachable data 💡 If something is still referenced, it won’t be cleaned 🔹 Common Memory Leak Scenarios ⚠️ Even with GC, leaks can happen: • Global variables • Closures holding large data • Unstopped setInterval / setTimeout • Detached DOM elements 🔹 How to Avoid Memory Issues ✅ Use let/const ✅ Clear timers (clearInterval / clearTimeout) ✅ Remove unused event listeners ✅ Avoid unnecessary references ✅ Use Chrome DevTools → Memory tab 🔹 Pro Tip 💡 Performance issues are often not slow code — they’re memory that never gets released 🚀 Final Thought Understanding Stack vs Heap gives you a huge edge in debugging and building scalable apps 💬 Have you ever faced a memory leak? What caused it? #JavaScript #WebDevelopment #Frontend #Performance #CodingTips #SoftwareEngineering
To view or add a comment, sign in
-
-
JS Object vs. Map: Why simple {} might be slow In JavaScript, we often default to using simple objects {} as dictionaries. Most of the time, it works just fine. But there’s a tipping point where choice of data structure directly impacts both performance and code maintainability. I recently refactored a module in one of Node.js services and here is why we should choose Map for heavy-duty tasks: Non-String Keys: In an Object, keys are limited to Strings or Symbols. In a Map, a key can be anything - an object, an array, or even a function. This is a game-changer for metadata caching. Performance: Map is specifically optimized for frequent additions and removals. If your service handles high-frequency data updates, the performance gap becomes noticeable. Predictable Iteration: Unlike Objects, Map always preserves the insertion order of elements. Built-in Size: No more Object.keys(obj).length. You get the size instantly with .size. The bottleneck: We needed to maintain an in-memory cache for user sessions where the key was a complex device configuration object. Initially, we used JSON.stringify(config) to create string keys. The result was massive CPU overhead on serialization and slower lookups as the cache grew. The solution: By switching to a Map, we used the configuration object itself as the key. No serialization, O(1) lookup time, and much cleaner code. #javascript #nodejs #backend #performance #cleancode #Map #datastructures
To view or add a comment, sign in
-
-
𝐈𝐬 𝐲𝐨𝐮𝐫 `𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭` 𝐟𝐢𝐫𝐢𝐧𝐠 𝐰𝐚𝐲 𝐭𝐨𝐨 𝐨𝐟𝐭𝐞𝐧? 𝐘𝐨𝐮 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐟𝐚𝐥𝐥𝐢𝐧𝐠 𝐟𝐨𝐫 𝐚 𝐜𝐨𝐦𝐦𝐨𝐧 𝐝𝐞𝐩𝐞𝐧𝐝𝐞𝐧𝐜𝐲 𝐚𝐫𝐫𝐚𝐲 𝐭𝐫𝐚𝐩. We've all been there: you put an object or array into your `useEffect`'s dependency array, thinking it's stable. But because JavaScript compares objects and arrays by reference, even if their content is identical, `useEffect` sees a new object on every render and re-runs your effect. This can lead to performance hits, stale data, or even infinite loops. 🚫 The Problem: ```javascript function MyComponent({ data }) { const options = { id: data.id, filter: 'active' }; useEffect(() => { // This runs every render if 'options' object is new fetchData(options); }, [options]); // 'options' is a new object reference each time // ... } ``` ✅ The Fix: Stabilize with `useMemo` If your object or array doesn't logically change across renders (or only changes based on specific primitives), wrap it in `useMemo`. This memoizes the object itself, ensuring its reference remains the same unless its dependencies actually change. ```javascript function MyComponent({ data }) { const stableOptions = useMemo(() => ({ id: data.id, filter: 'active' }), [data.id]); // Only re-create if data.id changes useEffect(() => { fetchData(stableOptions); }, [stableOptions]); // Now only re-runs if stableOptions' reference changes // ... } ``` This trick is a lifesaver for optimizing `useEffect` calls, especially when dealing with complex configurations or filtering logic passed down as props. It keeps your effects clean and your app performant. What's been your biggest `useEffect` headache, and how did you solve it? #React #FrontendDevelopment #JavaScript #Performance #WebDev
To view or add a comment, sign in
-
🚀 map() vs. forEach(): Do you know the difference? The Hook: One of the first things we learn in JavaScript is how to loop through arrays. But using the wrong method can lead to "hidden" bugs that are a nightmare to fix. 🛑 🔍 The Simple Difference: ✅ .map() is for Creating. Use it when you want to take an array and turn it into a new one (like doubling prices or changing names). It doesn't touch the original data. ✅ .forEach() is for Doing. Use it when you want to "do something" for each item, like printing a message in the console or saving data to a database. It doesn't give you anything back. 💡 Why should you care? 1. Clean Code: .map() is shorter and easier to read. 2. React Friendly: Modern frameworks love .map() because it creates new data instead of changing the old data (this is called Immutability). 3. Avoid Bugs: When you use .forEach() to build a new list, you have to create an empty array first and "push" items into it. It’s extra work and easy to mess up! ⚡ THE CHALLENGE (Test your knowledge! 🧠) Look at the image below. Most developers get this wrong because they forget how JavaScript handles "missing" returns. What do you think is the output? A) [4, 6] B) [undefined, 4, 6] C) [1, 4, 6] D) Error Write your answer in the comments! I’ll be replying to see who got it right. 👇 #JavaScript #JS #softwareEngineer #CodingTips #LearnToCode #Javascriptcommunity #Programming #CleanCode #CodingTips
To view or add a comment, sign in
-
-
🚨 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗧𝗿𝗮𝗽 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻𝘀 – 𝗣𝗮𝗿𝘁 𝟮 If you think you understand JavaScript… Try predicting these outputs 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗿𝘂𝗻𝗻𝗶𝗻𝗴 𝘁𝗵𝗲 𝗰𝗼𝗱𝗲 😏 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟭: 𝗛𝗼𝗶𝘀𝘁𝗶𝗻𝗴 𝗠𝘆𝘀𝘁𝗲𝗿𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎); 𝑣𝑎𝑟 𝑎 = 10; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑏); 𝑙𝑒𝑡 𝑏 = 20; 𝗢𝘂𝘁𝗽𝘂𝘁: undefined ReferenceError 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • var is hoisted and initialized with undefined • let is hoisted but stays in 𝗧𝗲𝗺𝗽𝗼𝗿𝗮𝗹 𝗗𝗲𝗮𝗱 𝗭𝗼𝗻𝗲 (𝗧𝗗𝗭) 👉 Accessing b before initialization throws an error. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟮: 𝗖𝗹𝗼𝘀𝘂𝗿𝗲𝘀 𝗶𝗻 𝗔𝗰𝘁𝗶𝗼𝗻 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑜𝑢𝑡𝑒𝑟() { 𝑙𝑒𝑡 𝑐𝑜𝑢𝑛𝑡 = 0; 𝑟𝑒𝑡𝑢𝑟𝑛 𝑓𝑢𝑛𝑐𝑡𝑖𝑜𝑛 𝑖𝑛𝑛𝑒𝑟() { 𝑐𝑜𝑢𝑛𝑡++; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑐𝑜𝑢𝑛𝑡); }; } 𝑐𝑜𝑛𝑠𝑡 𝑓𝑛 = 𝑜𝑢𝑡𝑒𝑟(); 𝑓𝑛(); 𝑓𝑛(); 𝑓𝑛(); 𝗢𝘂𝘁𝗽𝘂𝘁: 1 2 3 💡 𝗪𝗵𝘆? The inner function forms a 𝗰𝗹𝗼𝘀𝘂𝗿𝗲, remembering count even after outer() has finished execution. 👉 This is heavily used in 𝗥𝗲𝗮𝗰𝘁 𝗵𝗼𝗼𝗸𝘀 & 𝗿𝗲𝗮𝗹-𝘄𝗼𝗿𝗹𝗱 𝗮𝗽𝗽𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟯: 𝗣𝗿𝗼𝗺𝗶𝘀𝗲 𝘃𝘀 𝘀𝗲𝘁𝗧𝗶𝗺𝗲𝗼𝘂𝘁 (𝗘𝘃𝗲𝗻𝘁 𝗟𝗼𝗼𝗽) 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑆𝑡𝑎𝑟𝑡"); 𝑠𝑒𝑡𝑇𝑖𝑚𝑒𝑜𝑢𝑡(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑇𝑖𝑚𝑒𝑜𝑢𝑡"); }, 0); 𝑃𝑟𝑜𝑚𝑖𝑠𝑒.𝑟𝑒𝑠𝑜𝑙𝑣𝑒().𝑡ℎ𝑒𝑛(() => { 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝑃𝑟𝑜𝑚𝑖𝑠𝑒"); }); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔("𝐸𝑛𝑑"); 𝗢𝘂𝘁𝗽𝘂𝘁: Start End Promise Timeout 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 • Promise callbacks go to Microtask Queue • setTimeout goes to Macrotask Queue 👉 𝗠𝗶𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀 are executed before 𝗺𝗮𝗰𝗿𝗼𝘁𝗮𝘀𝗸𝘀. 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟰: 𝗧𝗿𝗶𝗰𝗸𝘆 𝗘𝗾𝘂𝗮𝗹𝗶𝘁𝘆 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] == 𝑓𝑎𝑙𝑠𝑒); 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔([] === 𝑓𝑎𝑙𝑠𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: true false 💡 𝗪𝗵𝘆? • == allows 𝘁𝘆𝗽𝗲 𝗰𝗼𝗲𝗿𝗰𝗶𝗼𝗻 • [] → "" → 0 and false → 0 → ✅ true • === checks strict equality (no coercion) → ❌ false 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻 𝟱: 𝗢𝗯𝗷𝗲𝗰𝘁 𝗥𝗲𝗳𝗲𝗿𝗲𝗻𝗰𝗲 𝗧𝗿𝗮𝗽 𝑐𝑜𝑛𝑠𝑡 𝑎 = { 𝑛𝑎𝑚𝑒: "𝐽𝑆" }; 𝑐𝑜𝑛𝑠𝑡 𝑏 = 𝑎; 𝑏.𝑛𝑎𝑚𝑒 = "𝑅𝑒𝑎𝑐𝑡"; 𝑐𝑜𝑛𝑠𝑜𝑙𝑒.𝑙𝑜𝑔(𝑎.𝑛𝑎𝑚𝑒); 𝗢𝘂𝘁𝗽𝘂𝘁: React 💡 𝗘𝘅𝗽𝗹𝗮𝗻𝗮𝘁𝗶𝗼𝗻 Objects are stored by reference, not value. Both a and b point to the 𝘀𝗮𝗺𝗲 𝗺𝗲𝗺𝗼𝗿𝘆 𝗹𝗼𝗰𝗮𝘁𝗶𝗼𝗻. 💬 𝗜𝗻𝘁𝗲𝗿𝘃𝗶𝗲𝘄 𝗜𝗻𝘀𝗶𝗴𝗵𝘁 If you can confidently answer these, you're ahead of 𝟴𝟬% 𝗼𝗳 𝗰𝗮𝗻𝗱𝗶𝗱𝗮𝘁𝗲𝘀. Most developers fail not because they don’t know JavaScript… But because they don’t understand its 𝗰𝗼𝗿𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿 𝗱𝗲𝗲𝗽𝗹𝘆. 🔥 𝗖𝗵𝗮𝗹𝗹𝗲𝗻𝗴𝗲 𝗳𝗼𝗿 𝗬𝗼𝘂 console.log(typeof null); console.log(typeof NaN); Drop your answers in the comments 👇 ♻️ Follow Shubham Kumar Raj for more such high-value interview content #javascript #frontenddeveloper #codinginterview #webdevelopment #programming #learnjavascript #100daysofcode #hiring
To view or add a comment, sign in
-
Day 09 (Project) : Fetching Real-World Data with JavaScript! 🌐💾 I’m excited to share my latest project—a dynamic "User Data List" application built with HTML, CSS, and JavaScript! This project was a deep dive into how modern web applications communicate with external servers. Key features of this project: • 📡 Fetch API: Implemented asynchronous requests to retrieve user information from a REST API. • ⏳ Loading State: Added a "Loading..." indicator to improve user experience while data is being fetched. • 📊 Dynamic Table Generation: Used JavaScript to iterate through the retrieved data and populate a clean, organized HTML table. • 🎨 Responsive UI: Designed a simple and intuitive interface for seamless data viewing. Mastering the Fetch API is a major step in my journey toward building full-stack applications. It’s amazing to see how a few lines of code can connect a webpage to a world of data! #JavaScript #WebDevelopment #FetchAPI #CodingJourney #FrontendDeveloper #Programming #TechSkills #LearningByDoing #Amarjeet Sir Gravity Coding
To view or add a comment, sign in
-
Node.js Worker Threads: True Multi-Threading for Your JavaScript Code Node.js is recognized for its efficient handling of I/O through the Event Loop and the UV_THREADPOOL for system-level tasks. However, when JavaScript code becomes the bottleneck, Worker Threads are essential. 🧠 Core Concepts: - Isolated Execution: Each worker operates in its own V8 instance with separate memory, functioning like lightweight parallel Node.js instances. - True Parallelism: Unlike the Event Loop, which is concurrent, Worker Threads enable parallel execution by utilizing multiple CPU cores. - Message-Based Communication: Workers communicate via postMessage(), ensuring no shared state by default, which reduces race conditions. 🛠 When to use them? - Avoid using Worker Threads for I/O, as the Event Loop is more efficient for that. Instead, utilize them for CPU-bound tasks that could otherwise "freeze" your app: - Heavy Math: Complex calculations or data science in JavaScript. - Data Parsing: Transforming large JSON or CSV files. - Image/Video: Processing buffers or generating reports. Key Takeaway: The Thread Pool manages system tasks, while Worker Threads enhance the performance of your JavaScript code. #NodeJS #Backend #Javascript #WebDev #SoftwareEngineering #Performance
To view or add a comment, sign in
-
-
🚀 Mastering Arrays in JavaScript: Understanding this fundamental data structure 📊 Arrays are collections of items stored in a single unit, allowing developers to store multiple values in a single variable. This makes it easy to organize and access related data efficiently in their code. For developers, understanding arrays is crucial as they are widely used in building applications to manage and manipulate data effectively. Let's break it down step by step: 1️⃣ Declare an array using square brackets [ ]. 2️⃣ Assign values to the array elements separated by commas. 3️⃣ Access elements by their index position, starting from 0. Full code example: ```javascript let fruits = ['apple', 'banana', 'orange']; console.log(fruits[0]); // Output: apple ``` Pro tip: Use array methods like 'push' and 'pop' to add or remove elements dynamically. Common mistake to avoid: Forgetting that array indices start at 0, leading to incorrect element access. 🌟 What's your favorite use case for arrays in your projects? Share below! 🌟 🌐 View my full portfolio and more dev resources at tharindunipun.lk #ArraysInJavaScript #DataStructures #WebDevelopment #JavaScriptTips #CodeNewbie #DevelopersCommunity #ArrayMethods #CodingSkills #tharindunipun
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