React : Ever Hit That “Stale Context in Effects” Bug? If you’ve ever needed to log analytics or track a page visit using context and useEffect, let me know if this sounds familiar: “I want to log the latest number of cart items every time a user navigates—but my effect always gets the old value unless I add everything in the dependency array...” Now, in React 19.2, the useEffectEvent hook makes this way easier! import { useEffect, useContext, useEffectEvent } from 'react'; function Page({ url }) { const { items } = useContext(ShoppingCartContext); const numberOfItems = items.length; const onNavigate = useEffectEvent((visitedUrl) => { logVisit(visitedUrl, numberOfItems); }); useEffect(() => { onNavigate(url); }, [url]); } What’s different? With classic useEffect, you’d have to put numberOfItems in the dependency array, rerunning every time it changed. With useEffectEvent, the function always sees the latest context, props, and state - no extra dependencies, no rerun headaches. Perfect for logging, analytics, or event-like side effects where you just want the latest value at call time, and not trigger new effect runs! Ever built a page log or analytics with context in React? Did you hit the old “stale value in effects” issue? React 19.2’s useEffectEvent is designed exactly for this! Ref Doc https://lnkd.in/g45256v2 #React192 #useEffectEvent #ReactJS #WebDev #Context #CodeSample
"Stale Context in Effects: How to Fix with useEffectEvent"
More Relevant Posts
-
𝗪𝗮𝗻𝘁 𝘁𝗼 𝗳𝗲𝘁𝗰𝗵 𝗱𝗮𝘁𝗮 𝘄𝗶𝘁𝗵𝗼𝘂𝘁 𝗯𝗹𝗼𝗰𝗸𝗶𝗻𝗴 𝘆𝗼𝘂𝗿 𝗨𝗜? 𝗧𝗿𝘆 𝗥𝗲𝗮𝗰𝘁 𝗦𝘂𝘀𝗽𝗲𝗻𝘀𝗲! Suspense lets you "wait" for async operations (like data fetching) without blocking the entire UI. No more loading spinners that freeze your app! How it works: → Wrap your async component with 𝗥𝗲𝗮𝗰𝘁.𝗦𝘂𝘀𝗽𝗲𝗻𝘀𝗲 → Use a "fallback" component (e.g., a spinner or skeleton screen) while data is loading → Once data is ready, React automatically swaps in the fully loaded component Benefits: • Improved user experience—only the relevant part of the UI waits for data • Cleaner code—no more manual loading states or conditional rendering • Seamless integration with React Query, SWR, or other data-fetching libraries Example: ``` <Suspense fallback={<Spinner />}> <AsyncComponent /> </Suspense> ``` Tip: Combine Suspense with 𝗥𝗲𝗮𝗰𝘁.𝗹𝗮𝘇𝘆 for even better performance. Load components only when they’re needed! 𝗥𝗲𝘀𝗼𝘂𝗿𝗰𝗲𝘀: • 𝗥𝗲𝗮𝗰𝘁 𝗱𝗼𝗰𝘀: https://lnkd.in/dUpifpQG • 𝗣𝗿𝗮𝗰𝘁𝗶𝗰𝗮𝗹 𝘁𝘂𝘁𝗼𝗿𝗶𝗮𝗹𝘀 𝗼𝗻 𝗦𝘂𝘀𝗽𝗲𝗻𝘀𝗲 + 𝗱𝗮𝘁𝗮 𝗳𝗲𝘁𝗰𝗵𝗶𝗻𝗴 #ReactJS #Suspense #DataFetching #WebDevelopment #JavaScript #Frontend #ReactDev
To view or add a comment, sign in
-
🔁 useMemo vs useCallback: The hooks that prevent React disasters After working with React for years, here's what most developers get wrong about these hooks (and why it matters). The Quick Version: useMemo: "Remember this VALUE" → Use for expensive calculations → Example: Filtering 10,000 products by search term useCallback: "Remember this FUNCTION" → Use when passing functions as props → Example: Event handlers passed to child components Real scenarios where these hooks matter: ✅ useCallback: Search bars triggering API calls ✅ useMemo: Sorting/filtering large datasets ✅ useCallback: Functions passed to React.memo components ✅ useMemo: Computing derived state from props When NOT to use them: ❌ Simple components with fast renders ❌ Functions only used locally (not passed down) ❌ "Just in case" optimization without measuring Debugging tip: If DevTools shows the same component rendering 100+ times per second, check your function dependencies in useEffect. So? These hooks aren't about premature optimization. They're about preventing specific bugs that happen when React's reactivity creates unintended loops. Read detailed blog: https://lnkd.in/g3aVs55B What's been your experience with these hooks? Where have they saved you (or where did you over-optimize)?
To view or add a comment, sign in
-
React 19 just made one of the biggest quality-of-life upgrades ever: data fetching without useEffect(). If you’ve been building with React for a while, you know the pain: You write useState to store data. You set up useEffect to fetch it. You pray your dependency array doesn’t break something. And then you still get that flicker between “loading” and “loaded.” React 19 changes that completely. Introducing use() — a brand-new hook that brings async fetching directly into the render phase. Here’s what that means: • React now pauses rendering when it encounters a Promise. • It waits for it to resolve without blocking the rest of the UI. • Once data arrives, it resumes rendering with the final content. No flicker. No double render. No manual states or effects. This changes everything about how we fetch data: • No more useEffect just for API calls • No local state to hold results • No dependency debugging • No try/catch — errors automatically flow to the nearest ErrorBoundary React 19’s use() makes async data a first-class part of rendering. Fetching, refetching, and error handling — all handled natively by React itself. Less boilerplate. More predictability. Cleaner UI flow. This is the React we always wanted. I’ve attached a visual breakdown to make it easier to understand. What’s your take? Does use() finally solve React’s biggest headache? #React19 #ReactJS #ReactHooks #WebDevelopment #FrontendDevelopment #JavaScript #Frontend #Coding #DeveloperExperience #ReactTips
To view or add a comment, sign in
-
-
I build a simple JSON Viewer and here's how it can help you. Many devs complain that they don't have a simple JSON viewer tool that can show them how their data is structured. I got tired of that too. Why I built this: Every developer I know (including me) deals with JSON daily. But we're all using random websites that: ❌ Send our data who-knows-where ❌ Have terrible UX ❌ Crash on large files So I built something just for that but better → https://lnkd.in/d8K7j3BT What it does: Paste messy JSON → Click Parse → Get beautiful formatted output → Copy it That's literally it. No ads, no tracking, nothing. If the data is missing a comma or } somewhere, it will return an error telling you the line so you can quickly adjust My solution runs 100% in your browser or you can use my live github page and your data never leaves your machine. Tech I used: React (because components) CSS3 animations (design focused 🌊 easy on the eyes) GitHub Pages (lite, simple and free hosting FTW - every developer knows it) The best part? I kept it simple. No feature creep. No "enterprise" bloat. Just one tool that does one thing really, really well. Try it → https://lnkd.in/d8K7j3BT Question for you: What's the most annoying dev tool you use regularly? Drop it below - maybe I'll build a better version 👇 P.S. It's open source. Star it, fork it, roast my code - I'm here for all of it 😄 #WebDevelopment #React #JavaScript #DevTools #BuildInPublic
To view or add a comment, sign in
-
-
⚛️ Mastering React’s useReducer Hook 💡 When your component’s state logic starts getting complex — it’s time to move beyond useState. That’s where useReducer steps in 🚀 🔹 What is useReducer? useReducer is a React Hook used to manage complex or multiple related states in a clean, predictable way. It works just like a mini Redux inside your component 🎯 ⚙️ Syntax const [state, dispatch] = useReducer(reducer, initialState); 🧠 state → Current data 🎯 dispatch → Function to trigger actions ⚙️ reducer → Function that decides how the state should update 🧩 Example: Counter App import React, { useReducer } from "react"; const initialState = { count: 0 }; function reducer(state, action) { switch (action.type) { case "increment": return { count: state.count + 1 }; case "decrement": return { count: state.count - 1 }; default: return state; } } export default function Counter() { const [state, dispatch] = useReducer(reducer, initialState); return ( <div style={{ textAlign: "center" }}> <h2>Count: {state.count}</h2> <button onClick={() => dispatch({ type: "increment" })}>➕ Increment</button> <button onClick={() => dispatch({ type: "decrement" })}>➖ Decrement</button> </div> ); } 🌟 Why use useReducer? ✅ Perfect for complex state logic ✅ Makes code cleaner and organized ✅ Helps manage multiple state updates together ✅ Feels similar to Redux, but simpler 🔥 💬 In short: "useReducer helps you manage complex states more efficiently, giving your React components structure, clarity, and power 💪"
To view or add a comment, sign in
-
🤯 Why does my component re-render even though props look the same?? I hit this issue while optimizing a data table. The child component kept re-rendering on every state change, even when the data looked identical. Here’s a simplified version: function Parent() { const [count, setCount] = useState(0); const filters = { status: "active" }; return ( <> <button onClick={() => setCount(c => c + 1)}>{count}</button> <Table filters={filters} /> </> ); } filters looks the same every render, right? But React thinks it’s new every time - because a new object is created on each render. 🧠The Root Cause React uses shallow comparison for props. Even if two objects have identical content, their references are different - and that’s enough to trigger a re-render. ✅The Fix Stabilize your props using useMemo or useCallback: const filters = useMemo(() => ({ status: "active" }), []); Now filters keeps the same reference between renders 💡 Takeaway > React re-renders not because of what’s inside your props, but because of what they point to. Stability in references = stability in performance. 🗣️ Your Turn Have you ever chased a “mystery re-render” before? What tools do you use to debug them - React DevTools, why-did-you-render, or console logs? #ReactJS #WebDevelopment #FrontendDevelopment #PerformanceOptimization #CleanCode #JavaScript #ReactHooks #DevCommunity #LearnInPublic
To view or add a comment, sign in
-
Error Handling in Async/Await (try...catch in JavaScript) When using Async/Await, handling errors properly is just as important as handling data. That’s where the try...catch block shines It helps you catch and manage errors without crashing your app. Definition: try — contains the code that may throw an error. catch — handles the error gracefully when something goes wrong. Example: function fetchData(success) { return new Promise((resolve, reject) => { setTimeout(() => { if (success) resolve("✅ Data fetched successfully"); else reject("❌ Failed to fetch data"); }, 1000); }); } async function getData() { try { console.log("Fetching data..."); const result = await fetchData(false); // change to true to test success console.log(result); } catch (error) { console.error("Error caught:", error); } finally { console.log("Operation completed ✅"); } } getData(); Output (if failed): Fetching data... Error caught: ❌ Failed to fetch data Operation completed ✅ ⚙️ Why it’s useful: ✅ Prevents app crashes ✅ Keeps async code clean ✅ Helps in debugging network/API issues ✅ Works beautifully with multiple awaits 🔖 #JavaScript #AsyncAwait #ErrorHandling #TryCatch #WebDevelopment #Frontend #CodingTips #AsyncProgramming #JSConcepts #100DaysOfCode #LearnsJS #DeveloperJourney #WebDevCommunity
To view or add a comment, sign in
-
𝐓𝐨𝐝𝐚𝐲 𝐈 𝐥𝐞𝐯𝐞𝐥𝐞𝐝 𝐮𝐩 𝐦𝐲 𝐑𝐞𝐚𝐜𝐭 𝐬𝐤𝐢𝐥𝐥𝐬 𝐛𝐲 𝐢𝐦𝐩𝐥𝐞𝐦𝐞𝐧𝐭𝐢𝐧𝐠 𝐬𝐦𝐨𝐨𝐭𝐡, 𝐟𝐥𝐢𝐜𝐤𝐞𝐫-𝐟𝐫𝐞𝐞 𝐩𝐚𝐠𝐢𝐧𝐚𝐭𝐢𝐨𝐧 𝐮𝐬𝐢𝐧𝐠 𝐑𝐞𝐚𝐜𝐭 𝐐𝐮𝐞𝐫𝐲! I was exploring how to load API data page-by-page without the UI blinking or resetting and React Query’s 𝒌𝒆𝒆𝒑𝑷𝒓𝒆𝒗𝒊𝒐𝒖𝒔𝑫𝒂𝒕𝒂 feature completely changed the game for me. 🔥 What I Built - Dynamic Pagination using useState - Data Fetching with useQuery - Personalized API calls using pageNumber - Smooth transitions using keepPreviousData - Clean, minimal UI for posts + pagination buttons - Proper error & loading handling What I Learned 🔹 React Query refetches only when queryKey changes → ["posts", pageNumber] 🔹 queryFn should always be a function → () => FetchPosts(pageNumber) 🔹 API must receive the correct page number to return limited results 🔹 keepPreviousData helps avoid UI jumps and blank screens 🔹 Good CSS structure matters — it prevents overlapping and maintains layout 🎯 Outcome A smooth, modern, user-friendly pagination UI where: ✨ No flickering ✨ No layout shifting ✨ Old data stays visible while new data loads ✨ Perfect experience for users 🛠️ 𝑻𝒆𝒄𝒉 𝑺𝒕𝒂𝒄𝒌 : React.js, React Query, Axios, JSONPlaceholder API, Custom CSS I’m really enjoying diving deeper into React Query — the amount of control it gives over data fetching is incredible! Excited to keep building and learning more every day! #react #reactjs #reactquery #webdevelopment #frontenddeveloper #learningjourney #javascript
To view or add a comment, sign in
-
🚀 Next.js Magic: "getStaticProps" vs "getServerSideProps" If you’ve ever wondered when to use which — here’s the breakdown 👇 🧱 "getStaticProps" — Static Site Generation (SSG) - Runs at build time - Generates HTML + JSON once and reuses it for every request - Super fast — because content is served via CDN - Ideal for: ✅ Blogs ✅ Marketing pages ✅ Docs or FAQs 🕓 Optional: Add "revalidate" to enable Incremental Static Regeneration (ISR) — allowing static pages to update after deployment without a full rebuild. export async function getStaticProps() { const data = await fetch('https://lnkd.in/gMYFrdHq'); return { props: { data }, revalidate: 10 }; } --- 🌐 "getServerSideProps" — Server-Side Rendering (SSR) - Runs on every request - HTML is generated on the server, sent to the browser - Slower than SSG but always up-to-date - Ideal for: ✅ Dashboards ✅ Personalized data (user/session-based) ✅ Real-time content export async function getServerSideProps(context) { const data = await fetch('https://lnkd.in/gcyj7Xhk' + context.query.id); return { props: { data } }; } --- 💡 TL;DR - Use "getStaticProps" when data rarely changes (speed > freshness) - Use "getServerSideProps" when data changes frequently (freshness > speed) ⚡️ Next.js gives you the best of both worlds — choose wisely for performance + user experience. #Nextjs #WebDevelopment #Frontend #React #Performance #JavaScript
To view or add a comment, sign in
-
Today, I explored how to make websites more interactive and data-driven by integrating external APIs. Instead of relying on static content, I learned how to fetch and display real-time data — adding depth and functionality to the web experience. 🔹 Objective: Integrate external data sources to provide dynamic, real-time content. 🔹 Key Steps: 1️⃣ Selected a public API (like JSONPlaceholder) and explored its endpoints. 2️⃣ Used the fetch() function in script.js to retrieve data asynchronously. 3️⃣ Parsed the JSON response and dynamically updated the DOM to show live content. 💡 Takeaway: APIs unlock endless possibilities — from fetching user data to displaying live updates. This exercise deepened my understanding of asynchronous JavaScript and real-world data handling. #CognifyzTechnologies #WebDevelopment #JavaScript #APIIntegration #FrontendDevelopment #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