🚀 𝐌𝐚𝐬𝐭𝐞𝐫𝐢𝐧𝐠 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 𝐢𝐧 𝐑𝐞𝐚𝐜𝐭: 𝐓𝐡𝐞 𝐅𝐨𝐮𝐧𝐝𝐚𝐭𝐢𝐨𝐧 𝐨𝐟 𝐃𝐲𝐧𝐚𝐦𝐢𝐜 𝐀𝐩𝐩𝐬 Ever wondered how a simple click can change a whole webpage? That’s the magic of State. In React, useState is the most fundamental Hook you’ll use to bring your interfaces to life. 🔹 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞? It’s a Hook that allows you to add state to functional components. When the state changes, React automatically re-renders the component to reflect the new data. 🔹 𝐓𝐡𝐞 𝐒𝐲𝐧𝐭𝐚𝐱 const [state, setState] = useState(initialValue); -- state: The current value. -- setState: The function to update the value. -- initialValue: The starting point (number, string, etc.). 🔹 𝐒𝐢𝐦𝐩𝐥𝐞 𝐂𝐨𝐮𝐧𝐭𝐞𝐫 𝐄𝐱𝐚𝐦𝐩𝐥𝐞 import React, { useState } from 'react'; function Counter() { const [count, setCount] = useState(0); return ( <div> <h1>𝐂𝐨𝐮𝐧𝐭: {count}</h1> <button onClick={() => setCount(count + 1)}>𝐈𝐧𝐜𝐫𝐞𝐦𝐞𝐧𝐭</button> </div> ); } 🔹 𝐏𝐫𝐨 𝐓𝐢𝐩𝐬 𝐟𝐨𝐫 𝐮𝐬𝐞𝐒𝐭𝐚𝐭𝐞 -- 𝐃𝐨𝐧'𝐭 𝐦𝐮𝐭𝐚𝐭𝐞 𝐬𝐭𝐚𝐭𝐞 𝐝𝐢𝐫𝐞𝐜𝐭𝐥𝐲: Never do count = count + 1. Always use the setter function (setCount). -- 𝐀𝐬𝐲𝐧𝐜𝐡𝐫𝐨𝐧𝐨𝐮𝐬 𝐍𝐚𝐭𝐮𝐫𝐞: State updates aren't immediate. Use functional updates if you need the previous state: setCount(prev => prev + 1). -- 𝐈𝐧𝐢𝐭𝐢𝐚𝐥 𝐑𝐞𝐧𝐝𝐞𝐫: The initial value is only used during the first render. 𝐖𝐡𝐚𝐭’𝐬 𝐭𝐡𝐞 𝐦𝐨𝐬𝐭 𝐜𝐨𝐦𝐩𝐥𝐞𝐱 𝐬𝐭𝐚𝐭𝐞 𝐲𝐨𝐮’𝐯𝐞 𝐦𝐚𝐧𝐚𝐠𝐞𝐝 𝐢𝐧 𝐚 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭? Let’s discuss in the comments! 👇 Feel free to reach me out for any career mentoring Naveen .G.R|CareerByteCode #ReactJS #WebDevelopment #MERNStack #CodingTips #Javascript #Frontend
Mastering useState in React: The Foundation of Dynamic Apps
More Relevant Posts
-
⚠️ One tricky thing in React that confused me at first: useEffect dependencies At first, I thought useEffect just runs magically. But the truth is very simple 👇 🧠 Think of useEffect like this: “React, run this code after render, and re‑run it only when I tell you to.” That “telling” happens through the dependency array. ✅ Examples (super simple) useEffect(() => { console.log("Runs once"); }, []); ➡️ Runs only when component mounts but for the below case useEffect(() => { console.log("Runs when count changes"); }, [count]); ➡️ Runs every time count changes 🚨 The tricky part If you use a variable inside useEffect but forget to add it as a dependency, React will use an old value (stale data). 🧠 Rule to remember: If you use it inside useEffect, it should be in the dependency array. Once I understood this, useEffect stopped feeling scary 😊 Just logic + clarity. #React #JavaScript #Hooks #useEffect #Frontend #LearningInPublic
To view or add a comment, sign in
-
You say you’re “comfortable with JavaScript”? Cool. Let’s test that. Answer these in the comments 👇 🧠 1. What will this output? Why? 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + []); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨([] + {}); 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨({} + []); Most developers get at least one wrong. ⚡ 2. Predict the output: 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘰𝘶𝘵𝘦𝘳() { 𝘭𝘦𝘵 𝘤𝘰𝘶𝘯𝘵 = 0; 𝘳𝘦𝘵𝘶𝘳𝘯 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘪𝘯𝘯𝘦𝘳() { 𝘤𝘰𝘶𝘯𝘵++; 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘤𝘰𝘶𝘯𝘵); }; } 𝘤𝘰𝘯𝘴𝘵 𝘧𝘯 = 𝘰𝘶𝘵𝘦𝘳(); 𝘧𝘯(); 𝘧𝘯(); 𝘧𝘯(); What concept is this testing? 🔥 3. What’s the difference between these two? 𝘖𝘣𝘫𝘦𝘤𝘵.𝘧𝘳𝘦𝘦𝘻𝘦(𝘰𝘣𝘫); 𝘖𝘣𝘫𝘦𝘤𝘵.𝘴𝘦𝘢𝘭(𝘰𝘣𝘫); When would you use one over the other in production? 🧩 4. True or False? 𝘵𝘺𝘱𝘦𝘰𝘧 𝘯𝘶𝘭𝘭 === "𝘰𝘣𝘫𝘦𝘤𝘵" 𝘐𝘧 𝘵𝘳𝘶𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 𝘐𝘧 𝘧𝘢𝘭𝘴𝘦 — 𝘦𝘹𝘱𝘭𝘢𝘪𝘯 𝘸𝘩𝘺. 🚀 5. Async trap — what happens here? 𝘢𝘴𝘺𝘯𝘤 𝘧𝘶𝘯𝘤𝘵𝘪𝘰𝘯 𝘵𝘦𝘴𝘵() { 𝘳𝘦𝘵𝘶𝘳𝘯 42; } 𝘤𝘰𝘯𝘴𝘰𝘭𝘦.𝘭𝘰𝘨(𝘵𝘦𝘴𝘵()); What exactly gets logged? If you can answer all 5 confidently, you’re not just “using” JavaScript. You understand it. Drop your answers below 👇 Let’s see who’s interview-ready. #javascript #frontenddeveloper #codinginterview #webdevelopment #softwareengineering #DAY73
To view or add a comment, sign in
-
7 Next.js mistakes I made so you don’t have to. 🔥 I spent 4 months debugging problems that shouldn’t have existed. Not because Next.js is hard. Because nobody told me I was doing it wrong. Here’s every mistake — and the fix — so you don’t waste the same time I did 👇 🔥 Mistake 1 — “use client” on everything I added it to every component “just to be safe.” It destroys your performance. Only leaf-level interactive components need it. Never layouts, never pages. 😫 Mistake 2 — Fetching data in useEffect I was writing useEffect(() => { fetch... }) in every page. Make your page async and fetch directly inside it. Data arrives with the HTML. Zero loading spinners. 🤔 Mistake 3 — Ignoring loading.tsx I spent hours building custom loading states. Then I discovered loading.tsx. Drop it next to any page and Next.js handles it automatically. I felt so stupid. 💥 Mistake 4 — Not using Suspense One slow database call was blocking my entire page. Wrap slow components in <Suspense> and stream everything else instantly while it loads. 🔐 Mistake 5 — Securing routes with useEffect I was doing useEffect(() => { if (!user) router.push('/login') }). The page flashes before the redirect. Use middleware.ts to block at the edge. No flash. No leak. I made all 5 of these in my first month. Most people never find out why their app feels slow or broken. Now you know. Which one were you making? Be honest — drop the number below 👇 Save this so you never make them again. 🔖 #NextJS #React #WebDevelopment #JavaScript #Frontend #Beginners #100DaysOfCode #NextJSTips #Programming #CleanCode #WebDev #CodingMistakes #LearnToCode
To view or add a comment, sign in
-
-
🚀 Callback Functions in JavaScript — Simple but Tricky! A callback function is a function passed as an argument to another function and executed later. 💡 Basic Example: function greet(name, callback) { console.log("Hi " + name); callback(); } function sayBye() { console.log("Goodbye!"); } greet("User", sayBye); 🧠 Output: Hi User Goodbye! 🔥 Question #1 (Hoisting Surprise): function test(callback) { callback(); } test(function () { console.log(a); var a = 10; }); 🧠 Output: undefined 📌 Reason: var a is hoisted but initialized as undefined. 🔥 Question #2 (Scope Trap): function outer(cb) { let x = 5; cb(); } outer(function () { console.log(x); }); 🧠 Output: ReferenceError: x is not defined 📌 Reason: Callback doesn’t have access to outer scope unless passed. 🔥 Question #3 (Async Behavior): console.log("Start"); setTimeout(function () { console.log("Callback"); }, 0); console.log("End"); 🧠 Output: Start End Callback 📌 Reason: Event loop pushes callback to queue (async behavior). 🔥 Quick Check Question #4: function execute(cb) { return cb(); } function sayHi() { return "Hi!"; } console.log(execute(sayHi)); 🧠 Output: Hi! ⚡ Key Takeaways: ✔ Callbacks are fundamental to async JS ✔ Execution context matters more than syntax #JavaScript #Frontend #WebDevelopment #InterviewPrep #Callbacks
To view or add a comment, sign in
-
𝐈𝐬 𝐲𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐫𝐮𝐧𝐧𝐢𝐧𝐠 𝐢𝐧𝐟𝐢𝐧𝐢𝐭𝐞𝐥𝐲 𝐨𝐫 𝐦𝐨𝐫𝐞 𝐭𝐡𝐚𝐧 𝐢𝐭 𝐬𝐡𝐨𝐮𝐥𝐝? 𝐓𝐡𝐞 𝐜𝐮𝐥𝐩𝐫𝐢𝐭 𝐢𝐬 𝐨𝐟𝐭𝐞𝐧 𝐬𝐢𝐦𝐩𝐥𝐞𝐫 𝐭𝐡𝐚𝐧 𝐲𝐨𝐮 𝐭𝐡𝐢𝐧𝐤. One of the most common pitfalls with `useEffect` in React is including non-primitive values (objects, arrays, functions) directly in its dependency array without proper handling. Every time your component re-renders, if you create a new object or array literal, or a new function instance, its reference changes. ```javascript useEffect(() => { /* fetch data using config */ }, [config]); ``` If `config` is an object created directly inside your component, even if its properties are identical, `useEffect` sees a new object reference on every render. This forces the effect to re-run, leading to unnecessary computation, API calls, or even infinite loops. **The Fix:** 1. **Destructure Primitives:** If you only need specific primitive properties from an object, destructure them out and add only those to the dependency array. ```javascript const { baseUrl, timeout } = apiConfig; ``` ```javascript useEffect(() => { // ... use baseUrl, timeout }, [baseUrl, timeout]); ``` 2. **Memoize Objects/Arrays:** If the entire object/array is a dependency and is derived from stable values, use `useMemo` to memoize its creation. This ensures its reference remains stable across renders unless its own dependencies change. ```javascript const stableConfig = useMemo(() => ({ baseUrl: '/api', timeout: 5000 }), []); ``` ```javascript useEffect(() => { // ... use stableConfig }, [stableConfig]); ``` 3. **Memoize Functions:** For functions, use `useCallback` to prevent new function instances on every render, ensuring a stable reference for your dependency array. Understanding how JavaScript handles reference equality is key to mastering `useEffect` and writing performant React applications. What's your go-to strategy for managing complex `useEffect` dependencies? #React #ReactJS #Frontend #JavaScript #WebDevelopment #Performance
To view or add a comment, sign in
-
𝐀𝐫𝐞 𝐲𝐨𝐮 𝐛𝐚𝐭𝐭𝐥𝐢𝐧𝐠 𝐩𝐡𝐚𝐧𝐭𝐨𝐦 𝐛𝐮𝐠𝐬 𝐢𝐧 𝐲𝐨𝐮𝐫 𝐑𝐞𝐚𝐜𝐭 𝐜𝐨𝐦𝐩𝐨𝐧𝐞𝐧𝐭𝐬? 𝐘𝐨𝐮𝐫 𝐮𝐬𝐞𝐄𝐟𝐟𝐞𝐜𝐭 𝐦𝐢𝐠𝐡𝐭 𝐛𝐞 𝐬𝐢𝐥𝐞𝐧𝐭𝐥𝐲 𝐥𝐲𝐢𝐧𝐠 𝐭𝐨 𝐲𝐨𝐮. Often, we forget that `useEffect` captures variables from its surrounding scope. If those variables change but aren't in the dependency array, your effect might run with stale values from a previous render. This leads to subtle, hard-to-trace bugs where your logic seems correct but the data is wrong. Example: ```javascript function MyComponent({ userId }) { const [data, setData] = useState(null); // Problematic: Forgetting 'userId' in dependencies useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); // userId is referenced, but not in dependency array }, []); // <-- STALE CLOSURE if userId changes! // Correct: userId is a dependency useEffect(() => { fetch(`/api/users/${userId}/data`).then(res => res.json()).then(setData); }, [userId]); // <-- Correctly re-runs when userId changes } ``` The linter usually warns you about this, but it's easy to dismiss or override. Understanding why it warns you about missing dependencies is crucial for stable and performant React applications. It’s not just about avoiding infinite loops; it's about guaranteeing your effects always operate with the latest state and props. What's your most common `useEffect` pitfall, or a bug that took you ages to trace back to a stale closure? #React #Frontend #TypeScript #JavaScript #WebDevelopment
To view or add a comment, sign in
-
🚀 JavaScript Tips Every Developer Should Know 1️⃣ Use === instead of == Avoid unexpected type coercion. 0 == false // true ❌ 0 === false // false ✅ 2️⃣ Destructuring = Cleaner Code const user = { name: "Sam", age: 25 }; const { name, age } = user; 3️⃣ Default Parameters function greet(name = "Guest") { return `Hello ${name}`; } 4️⃣ Use Optional Chaining (?.) Prevents runtime errors. user?.address?.city 5️⃣ Use map, filter, reduce instead of loops Cleaner & functional approach. 6️⃣ Debounce API calls for performance Avoid unnecessary repeated calls (important in search inputs). 7️⃣ Use let & const instead of var Better scope control and avoids bugs. 💡 Small improvements in code → Big impact in performance & readability. #JavaScript #WebDevelopment #Frontend #CodingTips #Developers
To view or add a comment, sign in
-
𝗦𝗺𝗮𝗹𝗹 𝗪𝗶𝗻, 𝗕𝗶𝗴 𝗟𝗲𝗮𝗿𝗻𝗶𝗻𝗴, 𝗡𝗲𝘅𝘁.𝗷𝘀 𝗥𝗼𝘂𝘁𝗶𝗻𝗴 𝗚𝗼𝘁𝗰𝗵𝗮 Today I was working on an email navigation feature, the kind where you click through a list and the URL updates to reflect the selected item. The data was already fetched. No need to reload the page. I just wanted to update the URL silently. Simple, right? 𝗔𝘁𝘁𝗲𝗺𝗽𝘁 (𝗮𝘀 𝗺𝗲𝗻𝘁𝗶𝗼𝗻𝗲𝗱 𝗶𝗻 𝗻𝗲𝘅𝘁 𝗷𝘀 𝗱𝗼𝗰𝘀): window.history.replaceState(null, '', newPath); Didn't work. 𝗪𝗵𝗮𝘁 𝗮𝗰𝘁𝘂𝗮𝗹𝗹𝘆 𝘄𝗼𝗿𝗸𝗲𝗱: window.history.replaceState( { ...window.history.state, as: newPath, url: newPath }, '', newPath, ); 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆: Sometimes the fix is one line. Finding that one line? That's the real work.😆 #NextJs #WebDevelopment #Frontend #JavaScript #React #TIL #SoftwareEngineering
To view or add a comment, sign in
-
𝗪𝗵𝘆 𝘁𝘆𝗽𝗲𝗼𝗳 𝗻𝘂𝗹𝗹 𝗶𝘀 "𝗼𝗯𝗷𝗲𝗰𝘁" — 𝗧𝗵𝗲 𝟯𝟬-𝗬𝗲𝗮𝗿 𝗕𝘂𝗴 𝗧𝗵𝗮𝘁 𝗪𝗼𝗻’𝘁 𝗗𝗶𝗲 🐛 If you’ve ever debugged JavaScript and seen typeof null === 'object', you probably thought your code was broken. It’s not you. It’s one of the oldest "mistakes" in web history. Here’s the deep dive into why this quirk exists and why we’re stuck with it forever: 𝟭. 𝗧𝗵𝗲 "𝟭𝟬-𝗗𝗮𝘆" 𝗢𝗿𝗶𝗴𝗶𝗻 𝗦𝘁𝗼𝗿𝘆 ⏱️ In 1995, Brendan Eich created JavaScript in just 10 days. In that rush, the engine's internal structure used a "type tag" system to identify data. ● 𝗢𝗯𝗷𝗲𝗰𝘁𝘀 were assigned the tag 000. ● 𝗻𝘂𝗹𝗹, representing a null pointer, was represented as all zeros (0x00). Because the engine checked for the 000 tag to identify objects, and null consists entirely of zero bits, the typeof operator incorrectly flagged it as an object. 𝟮. 𝗧𝗵𝗲 𝗔𝘁𝘁𝗲𝗺𝗽𝘁𝗲𝗱 𝗙𝗶𝘅 🛠️ There was actually a proposal to "fix" this in ECMAScript 6 so that typeof null would return 'null'. So, why didn't it happen? 𝟯. 𝗧𝗵𝗲 "𝗗𝗼𝗻'𝘁 𝗕𝗿𝗲𝗮𝗸 𝘁𝗵𝗲 𝗜𝗻𝘁𝗲𝗿𝗻𝗲𝘁" 𝗥𝘂𝗹𝗲 🌐 Backward compatibility is the golden rule of the web. Millions of websites and legacy libraries rely on this specific bug for their logic. Changing it now would "break the internet," causing countless sites to crash. As Brendan Eich himself noted: “𝘐𝘵’𝘴 𝘵𝘰𝘰 𝘭𝘢𝘵𝘦 𝘵𝘰 𝘧𝘪𝘹.” 𝗧𝗵𝗲 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆 𝗳𝗼𝗿 𝗗𝗲𝘃𝘀: ✅ Never use typeof to check for null. ✅ Always use strict equality: myVar === null. ✅ Pro Tip: To check if something is actually a valid object, use: myVar !== null && typeof myVar === 'object'. JavaScript isn’t perfect, but its quirks are what make its history so fascinating. What’s your "favorite" JavaScript bug or quirk? Let’s discuss in the comments! 👇 #JavaScript #WebDevelopment #Programming #SoftwareEngineering #CodingLife #TechHistory #Frontend
To view or add a comment, sign in
-
-
Why I switched from js-joda to date-fns for Date and Time 🤔 📅 On my last project, we were using two different date and time libraries: js-joda and date-fns. This made the code harder to read and support: two different APIs, two ways to work with dates, extra conversions. I decided we should keep only one library and chose date-fns. Here’s why date-fns worked better for us: ▪️Simple, functional API With date-fns you just call functions like addDays(date, 3) or format(date, 'dd.MM.yyyy'). You work with the native Date object, which is familiar to any JavaScript developer. ▪️Easier for new developers New people don’t have to learn js-joda types like LocalDate or ZonedDateTime. It’s much faster to start writing code when you only use Date + small helper functions. ▪️Less boilerplate and conversions Before, we often had to convert between js-joda objects and Date. With date-fns everything stays in one format, so there is less extra code and fewer mistakes. ▪️Good for bundle size date-fns supports tree-shaking 🔥 You import only the functions you actually use, so the bundle stays smaller. ▪️Lots of examples and community It’s easy to find examples, answers, and snippets for date-fns online. That saves time when you need to solve common tasks with dates and time. After we switched fully to date-fns, the codebase became more consistent and easier to maintain. 👍 📝 Sometimes the best choice is not the "most powerful" library, but the one that keeps the project simple and clear for the whole team. #React #JavaScript #TypeScript #Frontend #Date #DateTime
To view or add a comment, sign in
-
More from this author
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