𝗥𝗲𝗮𝗰𝘁.𝗷𝘀 𝗣𝗮𝗿𝘁 𝟰 (𝟮𝟬𝟮𝟲): 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗛𝗼𝗼𝗸𝘀 𝗗𝗲𝗲𝗽 𝗗𝗶𝘃𝗲 🔥 Hi everyone! 👋 In Part 3, we covered the core hooks: useState, useEffect, and useRef. Today, let’s master the 𝗔𝗱𝘃𝗮𝗻𝗰𝗲𝗱 𝗛𝗼𝗼𝗸𝘀 that separate good React devs from great ones 1) useReducer (Complex State Logic) 𝗪𝗵𝗮𝘁 𝗶𝘁 𝗱𝗼𝗲𝘀: Manages state with a reducer function, like useState on steroids. Think of it like a traffic controller, actions go in, state updates are predictable. Key points: • Best for multiple related state values • Logic lives outside the component (easier testing) • `dispatch(action)` instead of `setState(value)` • Pairs well with useContext for global state 📌 Examples: Shopping cart, large forms, multi-step flows, undo/redo. 𝘂𝘀𝗲𝗦𝘁𝗮𝘁𝗲 𝘃𝘀 𝘂𝘀𝗲𝗥𝗲𝗱𝘂𝗰𝗲𝗿 • useState → simple values • useReducer → complex transitions 2) useMemo (Expensive Computation Caching) 𝗪𝗵𝗮𝘁 𝗶𝘁 𝗱𝗼𝗲𝘀: Memoizes a computed value, recalculates only when dependencies change. Like a calculator with memory, don’t redo work unnecessarily. Use it for: 1. Expensive computations (filtering/sorting big lists) 2. Stable derived values 3. Preventing unnecessary recalculations Don’t overuse: • It has overhead • Profile first, optimize second 📌 Examples: Filtering 10k items, computing totals, chart data prep. 3) useCallback (Stable Function References) 𝗪𝗵𝗮𝘁 𝗶𝘁 𝗱𝗼𝗲𝘀: Returns a memoized function reference between renders. Why it matters: New function every render = child re-render. Use it when passing callbacks to memoized components. 𝘂𝘀𝗲𝗠𝗲𝗺𝗼 𝘃𝘀 𝘂𝘀𝗲𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸: • useMemo → caches a value • useCallback → caches a function 📌 Examples: onClick handlers, API functions passed as props, debounced handlers. 4) useContext (Global State Without Prop Drilling) Let's components access shared data without passing props through every level. Think Wi-Fi connects without cables. 3-step pattern: 1. createContext() 2. Provider 3. useContext() Common uses: • Theme • Auth state • Language • Feature flags Tip: Combine with useReducer for a lightweight global store. 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗧𝗶𝗽𝘀 • React.memo — skip re-renders if props don’t change • useCallback + React.memo — stable props • useMemo — skip heavy recalculations • React.lazy() + Suspense — code splitting • Use stable, unique keys in lists • 𝗚𝗼𝗹𝗱𝗲𝗻 𝗿𝘂𝗹𝗲: 𝗠𝗲𝗮𝘀𝘂𝗿𝗲 𝗯𝗲𝗳𝗼𝗿𝗲 𝗼𝗽𝘁𝗶𝗺𝗶𝘇𝗶𝗻𝗴. • 𝗥𝗲𝗮𝗰𝘁 𝗗𝗲𝘃𝗧𝗼𝗼𝗹𝘀 𝗣𝗿𝗼𝗳𝗶𝗹𝗲𝗿 𝗶𝘀 𝘆𝗼𝘂𝗿 𝗯𝗲𝘀𝘁 𝗳𝗿𝗶𝗲𝗻𝗱. 𝙽̲𝚎̲𝚡̲𝚝̲ ̲𝙿̲𝚘̲𝚜̲𝚝̲:̲ ̲𝙲̲𝚞̲𝚜̲𝚝̲𝚘̲𝚖̲ ̲𝙷̲𝚘̲𝚘̲𝚔̲𝚜̲,̲ ̲𝙱̲𝚞̲𝚒̲𝚕̲𝚍̲𝚒̲𝚗̲𝚐̲ ̲𝚁̲𝚎̲𝚞̲𝚜̲𝚊̲𝚋̲𝚕̲𝚎̲ ̲𝙻̲𝚘̲𝚐̲𝚒̲𝚌̲ ̲(̲𝚞̲𝚜̲𝚎̲𝙵̲𝚎̲𝚝̲𝚌̲𝚑̲,̲ ̲𝚞̲𝚜̲𝚎̲𝙳̲𝚎̲𝚋̲𝚘̲𝚞̲𝚗̲𝚌̲𝚎̲,̲ ̲𝚞̲𝚜̲𝚎̲𝙻̲𝚘̲𝚌̲𝚊̲𝚕̲𝚂̲𝚝̲𝚘̲𝚛̲𝚊̲𝚐̲𝚎̲,̲ ̲𝚞̲𝚜̲𝚎̲𝙵̲𝚘̲𝚛̲𝚖̲)̲ #ReactJS #JavaScript #ReactHooks #FrontendDevelopment #LearnReact
Mastering Advanced React Hooks: useReducer, useMemo, useCallback, and useContext
More Relevant Posts
-
One of the biggest misconceptions I see: “Signals make lifecycle irrelevant.” No — they just shift it. React controls UI lifecycle (Render → Commit) Signals control data lifecycle (invalidate → recompute → schedule) If you don't respect both boundaries, things break: - tearing - infinite renders - inconsistent updates This article is about drawing that line correctly. #react #webdevs #frontend #javascript #typescript #signals #reactivity
To view or add a comment, sign in
-
🛡️ 𝗡𝗲𝘅𝘁.𝗷𝘀 𝟭𝟲: 𝗦𝗲𝗰𝘂𝗿𝗶𝘁𝘆, 𝗟𝗼𝗴𝗶𝗰 & 𝗠𝘂𝗹𝘁𝗶-𝗧𝗲𝗻𝗮𝗻𝗰𝘆 𝟭. 𝗥𝗼𝘂𝘁𝗲 𝗛𝗮𝗻𝗱𝗹𝗲𝗿𝘀 (𝗿𝗼𝘂𝘁𝗲.𝘁𝘀) 𝘃𝘀. 𝗽𝗿𝗼𝘅𝘆.𝘁𝘀 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: When should logic reside in a proxy.ts versus a dedicated Route Handler? 𝗔𝗻𝘀𝘄𝗲𝗿: Think of proxy.ts as the Receptionist and route.ts as the Specialist. Use proxy.ts for cross-cutting concerns that happen before the request hits your app: Auth redirects, A/B testing rewrites, and Geolocation-based routing. Use Route Handlers for specific, publicly reachable API endpoints: Webhook listeners (Stripe), file generation (PDFs/CSVs), or acting as a "Backend for Frontend" (BFF) to aggregate data from multiple microservices. 𝟮. 𝗦𝗲𝗿𝘃𝗲𝗿 𝗔𝗰𝘁𝗶𝗼𝗻𝘀 𝘃𝘀. 𝗥𝗼𝘂𝘁𝗶𝗻𝗴 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: How can a Server Action trigger a redirect while maintaining client-side state? 𝗔𝗻𝘀𝘄𝗲𝗿: By using the redirect() function within the action. The Mechanism: In Next.js 16, redirect() triggers a Client-Side Navigation (Soft Nav). This means the browser doesn't do a full page reload; instead, the React state in your persistent layouts (like a navigation bar or sidebar) remains intact while the main content area switches. Pro-Tip: Use revalidatePath or revalidateTag before the redirect to ensure the user lands on a page with fresh data. 𝟯. 𝗘𝗱𝗴𝗲 𝗥𝘂𝗻𝘁𝗶𝗺𝗲 𝗖𝗼𝗻𝘀𝘁𝗿𝗮𝗶𝗻𝘁𝘀 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: Which Node.js libraries will fail in proxy.ts, and how do you architect around it? 𝗔𝗻𝘀𝘄𝗲𝗿: Any library relying on native C++ modules or filesystem access (fs, path, crypto, os) will fail in the Edge Runtime used by proxy.ts. The Fix: Use Web-standard polyfills (e.g., jose instead of jsonwebtoken for JWTs) or move the heavy computation to a Route Handler configured with the nodejs runtime. 𝟰. 𝗗𝘆𝗻𝗮𝗺𝗶𝗰 𝗠𝗲𝘁𝗮𝗱𝗮𝘁𝗮 & 𝗦𝗘𝗢 𝗣𝗲𝗿𝗳𝗼𝗿𝗺𝗮𝗻𝗰𝗲 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: How do you generate dynamic OG tags in an async route without blocking the initial paint? 𝗔𝗻𝘀𝘄𝗲𝗿: Use generateMetadata. The Internal Logic: In Next.js 16, metadata is streamed. For users, the UI renders immediately while metadata is injected asynchronously into the <body>. Next.js 16 detects bots and waits for generateMetadata to resolve, ensuring a fully SEO-optimized <head>. 𝟱. 𝗠𝘂𝗹𝘁𝗶-𝘁𝗲𝗻𝗮𝗻𝘁 𝗦𝘂𝗯𝗱𝗼𝗺𝗮𝗶𝗻 𝗦𝘁𝗿𝗮𝘁𝗲𝗴𝘆 𝗤𝘂𝗲𝘀𝘁𝗶𝗼𝗻: What is the most performant way to implement a multi-tenant strategy (e.g., tenant.app.com)? 𝗔𝗻𝘀𝘄𝗲𝗿: Middleware Rewriting. Step 1: In proxy.ts, extract the hostname and check it against a fast-access store (like Vercel KV or Redis). Step 2: Use NextResponse.rewrite() to map the subdomain to an internal dynamic route (e.g., acme.app.com rewritten to /tenants/acme). The Result: Users see clean subdomains while you use a single [tenant] directory to share logic and isolate data via slugs. Simple and organized. #NextJS16 #WebSecurity #MultiTenancy #ServerActions #FullStack #SoftwareArchitecture #Vercel #TechLead #TechInterview
To view or add a comment, sign in
-
𝑵𝒐𝒅𝒆.𝒋𝒔 𝑭𝑨𝑸 𝐐. 𝐖𝐡𝐲 𝐢𝐬 𝐍𝐨𝐝𝐞.𝐣𝐬 𝐒𝐢𝐧𝐠𝐥𝐞-𝐭𝐡𝐫𝐞𝐚𝐝𝐞𝐝? Node.js uses a single thread to efficiently handle asynchronous processing. The operation of asynchronous tasks in a single thread achieves better performance and scalability than typical thread-based approaches under usual web loads. 𝐐. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐭𝐡𝐞 𝐍𝐨𝐝𝐞.𝐣𝐬 𝐞𝐯𝐞𝐧𝐭 𝐥𝐨𝐨𝐩 ? The event loop is the core mechanism that enables Node.js to handle multiple tasks efficiently on a single thread. When you perform an operation like reading a file, Node.js doesn’t wait for the task to complete. Instead, it delegates the task to the operating system and moves on to handle other tasks in the queue. Once the task finishes, the event loop picks up the result and executes the associated callback function. This asynchronous, non-blocking approach is what makes Node.js highly scalable and efficient, especially for I/O-intensive tasks like serving multiple users or processing API requests. 𝐐. 𝐖𝐡𝐚𝐭 𝐚𝐫𝐞 𝐦𝐨𝐝𝐮𝐥𝐞𝐬 𝐢𝐧 𝐍𝐨𝐝𝐞.𝐣𝐬, 𝐚𝐧𝐝 𝐡𝐨𝐰 𝐝𝐨 𝐲𝐨𝐮 𝐮𝐬𝐞 𝐭𝐡𝐞𝐦 ? Modules in Node.js are reusable blocks of code that help organize functionality into smaller, manageable pieces. There are three types of modules: ⦿ Core Modules: Built into Node.js (e.g., fs, http, path) ⦿ Local Modules: Custom modules you create within your project ⦿ Third-Party Modules: Installed via npm (e.g., Express) Here’s an example of a local module. 𝘮𝘢𝘵𝘩.𝘫𝘴 function add(a, b) { return a + b; } module.exports = add; 𝘐𝘯 𝘢𝘱𝘱.𝘫𝘴 const add = require('./math'); console.log(add(2, 3)); // Output: 5 𝐐. 𝐖𝐡𝐚𝐭 𝐢𝐬 𝐑𝐄𝐏𝐋 𝐢𝐧 𝐭𝐡𝐞 𝐜𝐨𝐧𝐭𝐞𝐱𝐭 𝐨𝐟 𝐍𝐨𝐝𝐞.𝐣𝐬 ? In the Node.js framework, REPL is an abbreviation for Read, Eval, Print, and Loop. It’s an environment where one can interact by entering commands within it, similar to a console or Linux terminal and which prints out the system’s responses to commands. The tasks performed by REPL are as follows: • Read: The input from the user is read and parsed into a JavaScript data structure and then stored in memory. • Eval: The data structure is evaluated. • Print: The outcome of the evaluation is printed. • Loop: Continues on, running commands till the user presses CTRL+C twice. 𝐐. 𝐖𝐡𝐚𝐭 𝐚𝐫𝐞 𝐭𝐡𝐞 𝐅𝐞𝐚𝐭𝐮𝐫𝐞𝐬 𝐨𝐟 𝐍𝐨𝐝𝐞.𝐣𝐬 ? • Asynchronous and non-blocking I/O operations • Event-driven architecture • Single-threaded event loop • Scalability and high concurrency • Efficient module system with npm (Node Package Manager) • Cross-platform compatibility #javascript #nodejs #backend #fullstack #development #interview #readytowork #opentowork #immediateJoiner
To view or add a comment, sign in
-
💡 ASP.NET Core Clean Code Tip: Prefer Task Over void in Async Services When working with ASP.NET Core services, we often create asynchronous methods to call APIs or perform background operations. One small design choice can significantly improve maintainability and control of async operations. In the Home Controller, an AI service is injected and two endpoints are called before returning the view. The service methods might look like this: // In your AI Service public async void CallExternalEndpointAsync() { // ... logic that calls an external API await _httpClient.PostAsync("api/endpoint", data); } Why async void Should Be Avoided Uncontrolled Execution – Starts a fire-and-forget operation with no completion tracking. Cannot Be Awaited – The caller cannot wait for the operation to finish. // In your Home Controller public ActionResult Index() { // Calling the broken async method _aiService.CallExternalEndpointAsync(); // THIS LINE EXECUTES IMMEDIATELY, probably before the endpoint has even sent its request! return View(); } Exception Handling Issues – Errors cannot be caught by the calling code. Architecture Concerns – Breaks predictable contracts between controllers and services. While this works, there is a better approach for asynchronous methods in services. Recommended Approach Instead of returning void, return Task. public interface IAIService { // The return type is now Task, not void Task CallExternalEndpointAsync(); } public class AIService : IAIService { // The return type is now Task, not void public async Task CallExternalEndpointAsync() { // ... logic that calls an external API await _httpClient.PostAsync("api/endpoint", data); // No 'return' is needed; the compiler creates the Task for you. } } Even if the method does not return any data, returning Task provides important benefits. Why Task Is Preferred Returning Task allows the caller to: ✔ Await the method if needed ✔ Handle exceptions more reliably ✔ Know when the operation has completed ✔ Maintain better async flow in the application Example in the controller: // In your Home Controller public async Task<ActionResult> Index() // Note the async controller action { // Now you can AWAIT it! await _aiService.CallExternalEndpointAsync(); // This line ONLY executes after the async call has FULLY completed. return View(); } If it does not need to wait, it can simply call it without awaiting. This allows the method to behave similarly to a fire-and-forget operation when appropriate, while still preserving proper async design. Key Takeaway When designing async service methods in ASP.NET Core, it is generally recommended to use: async Task instead of async void This small design improvement helps keep the application cleaner, more predictable, and easier to maintain. #dotnet #aspnetcore #csharp #softwareengineering #cleanarchitecture #backenddevelopment #codingbestpractices #developercommunity #asyncawait
To view or add a comment, sign in
-
-
React Query changed how I think about frontend architecture. Before learning it deeply, my React apps looked like this: • `useEffect` everywhere • Manual loading states • Duplicate API calls • Complex global state The real problem? I was mixing server state with client state. Once I understood React Query architecture, everything became simpler. --- ## 🧠 Mental Model Think of React Query as a server state manager. Architecture: Server (API) ↓ React Query Cache ↓ React Components Your components never talk directly to the server. They talk to the cache layer. This small shift solves many problems automatically. --- ## ⚡ Query Flow When a component requests data: 1️⃣ React Query checks cache 2️⃣ If data exists → return instantly 3️⃣ If stale → re-fetch in background 4️⃣ Cache updates → UI re-renders This pattern is called: Stale-While-Revalidate Result: • Fast UI • Fresh data • Minimal API calls --- ## 🔄 Mutations (Writes) For updates like: • Add to cart • Update profile • Create order React Query uses mutations. Flow: User Action ↓ Mutation request ↓ Server update ↓ Invalidate related queries ↓ Refetch fresh data This keeps UI and backend in sync. --- ## 🚀 Prefetching Strategy One underrated feature is prefetching. Example: User opens product list. When they hover on a product → prefetch product details API. By the time they click → data already exists in cache. Navigation becomes instant. --- ## 🔥 Why This Matters When apps scale: Manual fetching leads to: ❌ API duplication ❌ inconsistent UI state ❌ difficult debugging React Query solves this by introducing a data architecture layer. Frontend starts behaving like a **distributed system client** instead of just UI. --- Now I’m designing frontend apps with: • Server state layer • Cache strategy • Query invalidation rules Instead of just writing fetch calls. --- 👉 Curious to know: Do you prefer **React Query** or **SWR** for server state management? #SystemDesign #Frontend #Backend #MERNStack #WebDev #FullStack #Developer #Web #Developer #Performance #Rendering #Express #JavaScript #BackendDev #Node #Mongo #Database #TanStack #Query #React
To view or add a comment, sign in
-
-
𝐈𝐟 𝐲𝐨𝐮'𝐫𝐞 𝐬𝐭𝐢𝐥𝐥 𝐰𝐫𝐞𝐬𝐭𝐥𝐢𝐧𝐠 𝐰𝐢𝐭𝐡 𝐚𝐧𝐲 𝐰𝐡𝐞𝐧 𝐦𝐚𝐩𝐩𝐢𝐧𝐠 𝐨𝐛𝐣𝐞𝐜𝐭 𝐩𝐫𝐨𝐩𝐞𝐫𝐭𝐢𝐞𝐬 𝐢𝐧 𝐓𝐲𝐩𝐞𝐒𝐜𝐫𝐢𝐩𝐭, 𝐲𝐨𝐮'𝐫𝐞 𝐦𝐢𝐬𝐬𝐢𝐧𝐠 𝐨𝐮𝐭. I've seen so many React components become any-land when trying to build reusable utilities that operate on object shapes. Like a generic Picker component that takes an array of objects and needs to extract a specific id or name field, but only if that field exists. The magic often lies in properly constraining your generics. Instead of `function getProperty<T>(obj: T, key: string)` (which loses all type safety for `key`), try `extends keyof T`. Example: ```typescript function pickProperty<T extends Record<string, any>, K extends keyof T>( items: T[], key: K ): T[K][] { return items.map(item => item[key]); } // Usage: interface User { id: string; name: string; email: string; } const users: User[] = [ /* ... */ ]; const userIds = pickProperty(users, 'id'); // Type: string[] // pickProperty(users, 'address'); // TS Error: 'address' does not exist on type 'User' ``` Here, `T extends Record<string, any>` ensures `T` is an object, and `K extends keyof T` makes sure `key` is a valid property of `T`. This gives you strong type inference and compiler errors where you need them. This pattern is a lifesaver for building type-safe, reusable data transformations in your React/Next.js applications, especially when dealing with API responses that share common structures. What's your go-to pattern for keeping object manipulations type-safe without falling back to any? Share your thoughts below! #TypeScript #React #FrontendDevelopment #Generics #WebDev
To view or add a comment, sign in
-
For a while now, I've been wanting to talk about Zod. Because once you truly use it — you wonder how you ever shipped without it. So here's the problem that makes Zod not just useful, but necessary. 👇 --- Your UI just went blank. No error. No warning. Just... nothing. 🫥 You check the console. Clean. You check your components. Fine. The bug was never in your UI — it was in the data. --- We all love TypeScript. But here's the gap nobody talks about enough: TypeScript is a compile-time guardian. The moment your app runs — it steps aside. So when an API returns malformed JSON, a form submits unexpected values, or an env variable is missing at startup? TypeScript has already left the building. 🚪 --- Here's the silent killer pattern: ❌ API returns a response ❌ TypeScript says "looks good" at compile time ❌ Runtime receives missing fields, nulls, or a shape change from the backend ❌ Your app renders a blank screen — with zero explanation Or worse — a form that passes bad data straight through. Or an app that boots fine locally — then crashes in production over a missing environment variable you didn't catch until 3 screens deep. --- The common band-aid? Null checks everywhere. optional chaining here → ?. conditional rendering there → && manual checks scattered across 20 components This doesn't fix the problem. It just hides it — while quietly turning your codebase into a maze. --- ✅ The real fix: Validate at the boundary. Centrally. Fail fast. Zod is a TypeScript-first schema validation library that works at runtime — filling exactly the gap TypeScript can't. With Zod, you can: → Define schemas for all API responses → Validate form inputs with the same schemas powering your types → Validate env variables at app startup — so bad config fails immediately, not silently → Reject or handle invalid data in ONE place → Infer TypeScript types directly from your schemas — no duplication → Let the rest of your app consume clean, predictable, safe data One library. Three boundaries protected. 🛡️ --- The result? ✦ No more blank screens from malformed API responses ✦ No more inconsistent form validation spread across components ✦ No more mysterious production crashes from missing env variables ✦ No more null checks cluttering your UI layer ✦ Cleaner code. Faster debugging. Stronger frontend-backend contracts. Think of API responses, form inputs, and environment config as the entry points into your system. Nothing should pass through unverified. --- TypeScript gives you confidence at build time. Zod gives you confidence at runtime. You need both. 🎯 Have you been caught off guard by a silent data bug, a bad form submission, or a missing env variable in prod? Drop it in the comments 👇 #Frontend #TypeScript #Zod #WebDevelopment #SoftwareEngineering #ReactJS #FormValidation #CleanCode #APIDevelopment
To view or add a comment, sign in
-
Next.js 16: Are you ready for the Async Request API and proxy.ts? 🛠️ Next.js 16 (2026) isn't just a performance bump—it’s a syntax shift. If you are moving from v14 or v15, your routing logic needs an update to stay compatible with the React Compiler and Turbopack. Here are the three most critical code patterns you need to know: 1️⃣ The New Async Request API In Next.js 16, params and searchParams are now Promises. You can no longer access them synchronously. This allows the framework to prioritize rendering static parts of your page while the dynamic data resolves. directory] // app/blog/[slug]/page.tsx export default async function Page({ params }: { params: Promise<{ slug: string }> }) { // ✅ Correct: You MUST await params const { slug } = await params; return <h1>Reading: {slug}</h1>; } 2️⃣ Goodbye middleware.ts, Hello proxy.ts Middleware has been evolved into proxy.ts. It lives at the edge and handles "Traffic Control." It is strictly for routing logic—not for heavy data processing. // src/proxy.ts import { NextResponse } from 'next/server'; import type { NextRequest } from 'next/request'; export async function proxy(req: NextRequest) { const token = req.cookies.get('session'); // Simple Redirect Logic if (!token && req.nextUrl.pathname.startsWith('/admin')) { return NextResponse.redirect(new URL('/login', req.url)); } return NextResponse.next(); } export const config = { matcher: ['/admin/:path*'], }; 3️⃣ The "use cache" Directive Next.js 16 stabilizes Partial Pre-rendering. You can now mark specific functions or components to be cached independently of the rest of the route. // components/PriceDisplay.tsx export default async function PriceDisplay() { "use cache"; // 🚀 This specific component is now cached at the edge const price = await getLatestPrice(); return <span>{price}</span>; } 💡 Strategy Cheat Sheet: Use proxy.ts for Auth guards, A/B testing, and Geolocation rewrites. Use Parallel Routes (@slot) when you need independent loading states for a dashboard (e.g., a Sidebar and a Main Feed). Use Intercepting Routes ((..)) for "Modals-as-Routes"—allowing users to share a URL that opens a specific item in a modal. The Bottom Line: Next.js 16 is pushing us toward a highly granular, asynchronous architecture. By awaiting your params and using the proxy.ts correctly, you're ensuring your app is ready for the React Compiler's aggressive optimizations. Are you finding the transition to Async APIs smooth, or is it breaking your existing utility functions? Let's debug in the comments! 👇 #NextJS16 #WebDev #ReactJS #CodingTips #FullStack #Vercel #JavaScript #SoftwareArchitecture
To view or add a comment, sign in
-
-
JavaScript Performance Optimization: Frequency Counter Pattern While revisiting common algorithm patterns, I compared two approaches to solve a classic problem: Question: Check if the second array contains the squares of the first array with the same frequency. Example: arr1 = [1,2,3,2] arr2 = [9,1,4,4] ❌Approach 1: Using indexOf() + splice() (Naive Solution) -This approach searches the second array for every element of the first array. function same(arr1, arr2){ if(arr1.length !== arr2.length){ return false; } for(let i = 0; i < arr1.length; i++){ let correctIndex = arr2.indexOf(arr1[i] ** 2) if(correctIndex === -1){ return false; } arr2.splice(correctIndex,1) } return true; } ✅ Approach 2: Frequency Counter Pattern (Optimized Solution) - Instead of repeatedly searching arrays, we count occurrences using objects (hash maps) function same(arr1, arr2){ if(arr1.length !== arr2.length){ return false; } let frequencyCounter1 = {} let frequencyCounter2 = {} for(let val of arr1){ frequencyCounter1[val] = (frequencyCounter1[val] || 0) + 1 } for(let val of arr2){ frequencyCounter2[val] = (frequencyCounter2[val] || 0) + 1 } for(let key in frequencyCounter1){ if(!(key ** 2 in frequencyCounter2)){ return false } if(frequencyCounter2[key ** 2] !== frequencyCounter1[key]){ return false } } return true } 🚀 Key Takeaway (Big O Notation) Instead of repeatedly searching arrays: ❌ Nested lookups → O(n²) ✅ Frequency Counter → O(n) A small algorithmic improvement can make a big difference in performance, especially when working with large datasets. 💬 Curious to hear from other developers — What are your favorite JavaScript optimization patterns? #JavaScript #FrontendDevelopment #Algorithms #PerformanceOptimization #CodingPatterns #WebDevelopment
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
👍🏻