🚀 Programmatic Navigation in React Router: useNavigate vs Navigate When building modern React apps, navigation isn’t always triggered by clicking a <Link />. Sometimes, you need to redirect users based on logic — after a form submission, authentication, or a condition. That’s where programmatic navigation comes in 👇 🔹 1. useNavigate (Imperative Navigation) Use this hook when you want to navigate after an action or event (e.g., button click, form submit). import { useNavigate } from "react-router-dom"; function Login() { const navigate = useNavigate(); function handleLogin() { // after successful login navigate("/dashboard"); } return <button onClick={handleLogin}>Login</button>; } 👉 Think of it as: "When this happens → go there." 🔹 2. <Navigate /> (Declarative Navigation) Use this when navigation depends on state or conditions during render. import { Navigate } from "react-router-dom"; function ProtectedRoute({ user }) { if (!user) return <Navigate to="/login" />; return <Dashboard />; } 👉 Think of it as: "If this is true → render a redirect." 💡 Key Difference useNavigate → triggered by events (imperative) <Navigate /> → triggered by state (declarative) 🔥 Pro Tip Use <Navigate /> for route protection and useNavigate for user-triggered flows like form submissions or button actions. Mastering both gives you full control over your app’s navigation flow — making your UI smarter and more dynamic 💪 #React #WebDevelopment #JavaScript #Frontend #ReactRouter #100DaysOfCode
React Navigation: useNavigate vs Navigate
More Relevant Posts
-
🚀 Enhancing Web App Performance with Easy Techniques When it comes to creating scalable web applications, optimizing performance is super important! Recently, I discovered three fantastic techniques that can really boost both performance and the user experience: 🔹 Debouncing Debouncing is a great way to delay API calls until the user has finished typing. 👉 For instance, in a search bar, rather than calling the API with every keystroke, we wait until the user completes their input. ✅ This reduces unnecessary API calls ✅ It makes everything run more efficiently 🔹 Lazy Loading Lazy loading means that components are only loaded when they’re actually needed. 👉 For example, in React, we can dynamically load pages or components as required. ✅ This cuts down the initial load time ✅ It enhances the speed of the application 🔹 Throttling Throttling is all about limiting how often a function can run within a certain timeframe. 👉 A great example is preventing multiple API calls when a user clicks a button repeatedly. ✅ This helps avoid server overload ✅ It boosts stability 💡 These tiny optimizations can really make a huge difference when building scalable, high-performance applications. #WebDevelopment #ReactJS #PerformanceOptimization #JavaScript #FullStackDeveloper #LearningInPublic
To view or add a comment, sign in
-
😩 I used to HATE when my entire website just... went white. No error. No message. Just a blank screen staring back at me. I'd spend hours trying to figure out what went wrong — refreshing, console-diving, questioning my life choices. 😅 The worst part? One small bug was taking down the ENTIRE app. Not just one section. Everything. Then I discovered Error Boundaries in React — and it changed how I build apps forever. 🙌 Here's what it does in simple terms: Instead of letting one broken component crash your whole UI, Error Boundary catches the error and shows a friendly fallback message — while keeping the rest of your app running perfectly. ✅ <ErrorBoundary fallback={<p>Oops! Something went wrong here.</p>}> <MyUnpredictableComponent /> </ErrorBoundary> Now instead of a white screen of death 💀 — my users see a clean message, and everything else on the page still works. I now wrap Error Boundaries around: 🔹 Third-party components I don't fully control 🔹 Data-heavy sections that depend on APIs 🔹 Any experimental features in production 🔹 Dashboard widgets that load independently It's one of those things nobody really talks about — but once you use it, you wonder how you ever shipped without it. If you've ever stared at a blank white screen wondering what went wrong — this is your sign to add Error Boundaries to your project TODAY. 🚀 Have you used Error Boundaries before? Or did you also suffer the white screen curse? 😂 Tell me in the comments! #ReactJS #WebDevelopment #Frontend #JavaScript #ErrorBoundary #SoftwareEngineering #React #
To view or add a comment, sign in
-
🗓️ Day 6 of 30 — Dynamic Routes & Params in Next.js Most real apps don't have fixed pages only. You need pages like: /blog/how-to-learn-nextjs /product/123 /user/zeeshan That's where Dynamic Routes come in. 📁 How it works in App Router: Instead of a fixed filename, you wrap it in square brackets: app/ └── blog/ └── [slug]/ └── page.tsx Now /blog/anything will match this route. 🎯 📦 Accessing the param: export default function BlogPost({ params, }: { params: { slug: string }; }) { return <h1>Post: {params.slug}</h1>; } Next.js automatically injects params — no extra setup needed. 🔁 What about multiple dynamic segments? app/shop/[category]/[productId]/page.tsx // params = { category: "shoes", productId: "42" } You can nest as many as you need. ⚡ Bonus — generateStaticParams: Want to pre-render dynamic pages at build time (for performance)? export async function generateStaticParams() { return [ { slug: "nextjs-basics" }, { slug: "dynamic-routes" }, ]; } This tells Next.js: "Hey, build these pages ahead of time." No waiting. Blazing fast. 🔥 💡 Key Takeaway: Dynamic routes let you build flexible, scalable pages without hardcoding every URL. One file → infinite pages. That's the power of Next.js. 📌 Follow for Day 7 tomorrow! What topic should I cover next? Drop it in the comments 👇 #NextJS #React #WebDevelopment #30DaysOfNextJS #Frontend #JavaScript #LearningInPublic
To view or add a comment, sign in
-
I stopped trusting the URL as the source of truth in my React app While building my latest expense tracker, I noticed a common pattern when working with dynamic routes. ➤ The Scenario: I’m using React Router for navigation and Context API for authentication. ⤷ My dashboard route was defined as: /dashboard/:username ➤ The Problem: Initially, I was reading the username directly from useParams(). It was only for UX purposes (I wanted to display the username in the URL). ⤷ But then I realized: → If a logged-in user manually changes the URL (e.g., /dashboard/ali), the UI state can become inconsistent with the authenticated user. → Even though the backend enforces authorization, the frontend should not treat the URL as the source of truth for user identity. ➤ The Fix: I made the Auth Context the single source of truth and added a guard to keep the UI in sync: ------------------------------------------------------- Dasboard.jsx useEffect(() => { if (user && username !== user) { navigate(`/dashboard/${user}`, { replace: true }); } }, [username, user, navigate]); ------------------------------------------------------- ➤ Key Takeaway: → The URL is user-controlled input → Auth state should always drive UI behavior → Keep your frontend consistent with the authentication layer Question I should ask experts: Is using URL params for display purposes (like usernames in routes) a good practice, or does it add unnecessary complexity in authenticated apps? #ReactJS #WebDevelopment #JavaScript #Frontend #SoftwareEngineering
To view or add a comment, sign in
-
-
Ever wondered how apps handle scroll events, button spam, or rapid user actions efficiently? 🤔 That’s where Throttling in JavaScript comes in. 💡 Throttling ensures that a function executes at a controlled rate, no matter how many times an event is triggered. Instead of running a function hundreds of times (like during scrolling), throttling limits execution to once every fixed interval — making your app much more efficient ⚡ 📌 Why it matters: Improves performance Prevents unnecessary function calls Enhances user experience 🚀 Common use cases: Scroll events Window resizing Mouse movements API calls on frequent triggers 🧠 Key takeaway: Throttling is about limiting execution frequency, not delaying it (that’s debounce 😉). Currently exploring more performance optimization techniques to build smoother and scalable web apps. #javascript #webdevelopment #frontend #reactjs #performance #coding
To view or add a comment, sign in
-
-
I just finished building a clean, responsive To-Do List App that focuses on simplicity and a seamless user experience. To make the app feel alive and interactive, I integrated React-Toastify, ensuring users get beautiful, real-time notifications whenever they add, complete, or delete a task. Key Features: ➕ Quick Task Entry: Add tasks instantly. 🔍 Smart Search: Filter through your list in real-time. ✅ Status Management: Mark tasks as complete or remove them with ease. 💾 Persistent Storage: Uses LocalStorage to keep your data safe even after a refresh. 📱 Fully Responsive: Optimized for a great experience on both mobile and desktop. 🔔 Interactive Alerts: Beautiful toast notifications for every action. Tech Stack Used: Frontend: React.js Styling: HTML5, CSS3 & Bootstrap (for Responsive) Notifications: React-Toastify Storage: Browser LocalStorage I’m constantly looking for ways to improve my workflow and build tools that are both functional and visually appealing. I’d love to get your feedback on this one! 🔗 https://lnkd.in/dXPA-6ed #ReactJS #WebDevelopment #FrontendDeveloper #Bootstrap #JavaScript #CodingLife #Programming #ReactToastify #PortfolioProject #Nxtwave #shrivjmodhacollege
To view or add a comment, sign in
-
Handling a single Promise is easy. Handling multiple Promises correctly is where things get interesting. In real-world apps, we often need to: • Wait for everything to complete • Pick the first successful result • React to the fastest response • Or simply collect all outcomes That’s exactly what Promise combinators solve. In my latest blog, I’ve explained: • Promise.all • Promise.any • Promise.race • Promise.allSettled Using a simple and relatable wedding planning analogy 💍 The goal was simple — make async logic feel intuitive, not intimidating. If you’ve ever been confused about these methods, this will help. Read here 👇 https://lnkd.in/gtcRWS5E Would love your feedback! #JavaScript #WebDevelopment #AsyncProgramming #Frontend
To view or add a comment, sign in
-
-
Your React App is Slow… and You Might Be the Reason Most developers use useMemo and React.memo but very few actually understand when NOT to use them ⚠️ I recently debugged a performance issue in a React dashboard. Everything looked optimized — but still, the UI was lagging. The reason? 👉 Memoization was used… but used wrongly. ⚡ Let’s break it down simply: 🔹 useMemo — Caches Calculations Use it when you have expensive computations Example: const filteredData = useMemo(() => { return data.filter(item => item.active); }, [data]); ✔ Prevents unnecessary recalculations ❌ Useless for cheap operations 🔹 React.memo — Stops Re-renders Wrap your component to avoid re-render when props don’t change const Card = React.memo(({ item }) => { return <div>{item.name}</div>; }); ✔ Great for large lists / heavy UI ❌ Useless if props change every render 🔥 The Real Problem Most people do this: Wrap everything in React.memo Add useMemo everywhere Hope performance improves 👉 Result: More complexity, same performance (sometimes worse) 💡 What Actually Works ✔ Use useMemo only for heavy calculations ✔ Use React.memo only when re-renders are costly ✔ Avoid passing new object/array references every render ✔ Measure performance before optimizing 🧠 The Mindset Shift Optimization is not about adding hooks It’s about removing unnecessary work 🚀 Final Takeaway Don’t optimize blindly. First understand: Why is it re-rendering? Is it actually slow? Then use the right tool. 👇 Curious — have you ever faced unnecessary re-renders in your app? #ReactJS #FrontendDevelopment #JavaScript #WebPerformance #ReactHooks #SoftwareEngineering #CleanCode #DevTips
To view or add a comment, sign in
-
-
🚀 Stop Wasting Renders in React — Optimize Your App Like a Pro One of the most overlooked performance issues in React apps is wasted renders. A wasted render happens when a component re-renders without any actual change in the UI. Everything looks the same… but under the hood, React is doing unnecessary work. 💡 And in large applications? That cost adds up quickly. ⚠️ Why Should You Care? Slower UI interactions Increased CPU usage Poor user experience (especially on low-end devices) 🧠 Common Causes of Wasted Renders 👉 Parent components re-rendering unnecessarily 👉 Passing new object/function references every render 👉 Not memoizing expensive computations 👉 Over-reliance on global state updates 🛠️ How to Fix It ✅ Use React.memo Prevents re-render when props haven’t changed ✅ Use useCallback for functions Avoids recreating functions on every render ✅ Use useMemo for expensive calculations Caches results instead of recalculating ✅ Avoid inline objects & arrays They create new references every time ✅ Split components smartly Smaller components = more controlled re-renders 🔍 Real Insight Not every re-render is bad. 👉 React is designed to re-render efficiently 👉 Optimization is only needed when there’s a real performance issue The goal is simple: Render only when it actually matters. 🧩 Final Thought Performance optimization isn’t about writing more code — it’s about writing smarter code. If your app feels slow, don’t guess… Profile it, measure it, then optimize it. #React #Frontend #WebDevelopment #Performance #JavaScript #SoftwareEngineering #CleanCode
To view or add a comment, sign in
-
-
🚀 How I reduced unnecessary re-renders in React (and improved performance) One common issue in React applications is unnecessary re-renders, which can slow down the UI — especially in large-scale apps. Here’s what worked for me: ✅ Used useCallback to memoize functions passed to child components ✅ Used useMemo to cache expensive computations ✅ Wrapped components with React.memo to prevent unnecessary updates ✅ Avoided inline functions and objects in JSX ✅ Optimized component structure to reduce prop changes 📈 Results: • Reduced unnecessary renders • Improved UI responsiveness • Better performance in data-heavy components 💡 Key takeaway: Performance optimization in React is not just about code — it’s about understanding how rendering works. What techniques have you used to optimize React apps? #React #Frontend #WebDevelopment #Performance #JavaScript #NextJS
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