Muhammad SharjeelSenior Software Engineer

Islamabad · --:--:--


Debugging Tips for Frontend Developers (React + Next.js)

Effective debugging is one of the most valuable skills for frontend developers. Here's a practical guide to debugging with logs, using the debugger keyword, troubleshooting APIs, and improving performance — with a special focus on React and Next.js.

Debugging isn't just fixing what's broken — it's about understanding the full lifecycle of your application. The earlier you learn this mindset, the faster you’ll grow as a developer.

Debugging with Logs

Logging is your first and simplest line of defense. Use console.log, console.error, and console.warn effectively to track what your code is doing at every step.

Example: Logging API Request/Response

async function fetchUserData() {
    console.log("Starting API call...");
    try {
      const response = await fetch('/api/user');
      const data = await response.json();
      console.log("API call success:", data);
      return data;
    } catch (error) {
      console.error("API call failed:", error);
    }
  }

Notice how we log before starting the call, and separately log the successful and error paths.

Using the debugger Keyword

When logging isn’t enough, the debugger keyword lets you pause code execution and inspect live values and the call stack in DevTools.

Example: Freezing the Code with Debugger

function calculateTotal(price, tax) {
    const total = price + tax;
    debugger; // Execution will pause here
    return total;
  }
  
  const finalAmount = calculateTotal(100, 20);
  console.log("Final Amount:", finalAmount);

When you reach debugger, the browser will pause execution. You can inspect variables like price, tax, and total right inside DevTools.

Debugging APIs and Network Issues

React and Next.js apps are API-heavy. Knowing how to debug API calls is crucial.

  • Always log the request payload and API response.
  • Check the Network tab in DevTools to inspect headers, status codes, and timings.
  • Look for common mistakes: incorrect URLs, missing auth headers, wrong HTTP methods, or parsing errors.

Example: API Call Debugging

async function loginUser(credentials) {
    console.log("Sending login request with credentials:", credentials);
    try {
      const res = await fetch('/api/login', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(credentials),
      });
      const result = await res.json();
      console.log("Login response:", result);
    } catch (error) {
      console.error("Login API failed:", error);
    }
  }

Checking API Response Time

Use the DevTools Network tab to analyze:

  • DNS Lookup
  • Connection time
  • Server processing time
  • Download time

Identify if slowness is happening on your end (frontend) or backend (server).

Special Tips for React and Next.js

In React:

  • Use React Developer Tools extension to inspect props and state visually.
  • Log inside useEffect to trace when effects re-run.

In Next.js:

  • Use console.log inside getServerSideProps and API Routes.
  • Remember that server-side logs appear in the Node.js terminal (not browser).

Real-World Debugging Scenario

Bug: Button Click Not Working

function MyButton() {
    const handleClick = () => {
      console.log("Button clicked!");
      // Suppose something is supposed to happen here
    };
  
    return (
      <button onClick={handleClick}>Click Me</button>
    );
  }

If clicking doesn't log anything:

  • Check if the event handler is wired correctly (onClick vs onclick typo?)
  • Use debugger inside handleClick to pause execution.
  • Check if any parent container is swallowing the event (like a preventDefault somewhere).

Building a Debugging Mindset

  • Don't guess. Observe and investigate.
  • Isolate issues. Comment out blocks to find culprits faster.
  • Master DevTools. Especially the Console, Network, and Sources tabs.
  • Read errors carefully. They usually tell you exactly what's wrong if you pay attention.

Tools to Amplify Your Debugging

  • React DevTools — Visualize component hierarchy, props, and state.
  • Redux DevTools — If using Redux, track actions and state changes easily.
  • VSCode Debugger — Set breakpoints directly inside your code editor for seamless inspection.

Final Thoughts

Great developers aren't the ones who never face bugs. They're the ones who debug efficiently and learn faster from every problem.

Master these debugging fundamentals now, and you'll separate yourself from the average developers much faster!

esc
HomeThe hero, the system map and selected workPageWorkAll 6 projects, each with a glimpse of its interfacePageAboutExperience, how I work and the stack I usePageWriting12 posts on engineering, AI and designPageGet in touchContact me by email or hire me on UpworkSection
Alara CodeTurns a client brief into a complete, human-approved software delivery pack.ProjectPolyXIdentity, tenancy and access platform shared by every product in the company.ProjectPolyX SDKTypeScript auth SDK on npm that puts the platform behind one typed client.ProjectAlara SpaceMulti-tenant team wiki that AI agents can read and write through MCP.ProjectAlara PlanProject tracker with AI meeting minutes, support intake and an MCP server.ProjectODINOmni-channel customer engagement platform on a microservices backend.Project
A portfolio that builds itself while you scrollThis site starts as a blank canvas and a swarm of cursors draws it in front of you. Here is why I wanted that, what it is made of, and everything that went wrong on the way.8 min readUnslopping AI output with nothing but a skillYou do not need a better model to get rid of the purple gradients. You need your taste written down as a skill the agent loads before it touches the screen.2 min readAI Assistant Coding vs Vibe CodingAs AI becomes ubiquitous in software development, a dangerous pattern is emerging: developers blindly accepting AI suggestions without understanding the code. This 'vibe coding' approach undermines the fundamentals of being a developer. Here's why understanding code matters more than shipping it, and how to use AI as a proper assistant.8 min readHosting Multiple Domains on One Server with Docker, NGINX & SSL (DevOps for Developers)As a full-stack developer, I recently had to deploy multiple backend services on one server, each with its own domain and SSL certificate. Here's how I combined Docker, NGINX, and Certbot to build a scalable, production-grade setup — without needing a dedicated DevOps engineer.3 min readTaming CORS in a Microservices Monorepo: From Async Validation to a Unified ConfigCORS errors can be frustrating, especially in a microservices monorepo setup. This blog dives into what CORS really is, why it matters, and how I solved the CORS challenge using a shared JSON config file — establishing a single source of truth for all services.4 min readDebugging Tips for Frontend Developers (React + Next.js)Effective debugging is one of the most valuable skills for frontend developers. Here's a practical guide to debugging with logs, using the debugger keyword, troubleshooting APIs, and improving performance — with a special focus on React and Next.js.3 min readIs the ‘AI Developer’ a Threat to Jobs – or a Marketing Stunt?AI dev tools are booming — but are they replacing developers or just reshaping workflows? Here's the balanced view.3 min readUsing Docker & NGINX to Build a Suite of MicroservicesExplore how to use Docker and NGINX to containerize and orchestrate a scalable microservices suite. Includes setup tips, architecture advice, and real-world tradeoffs.3 min readGetting Started with Next.js: Structure, Tips & DeploymentA developer-friendly introduction to Next.js — learn how to scaffold projects, understand folder structure, configure features, and deploy to Vercel seamlessly.3 min readGrid Systems: The Foundation of Great UI DesignWant cleaner, more balanced layouts? A grid system brings structure, rhythm, and clarity to your UI — and Tailwind makes it easier than ever to implement.2 min readUsing Generative AI to Speed Up Creative and Dev WorkflowsFrom ChatGPT to v0.dev — here's how generative AI helps streamline UI design, prototyping, coding, and problem-solving in modern workflows.3 min readWhat Is Accessible Design and Why It MattersAccessibility isn’t a nice-to-have. It’s a necessity. Here's why accessible design matters — and how to get it right in your UI and frontend code.3 min read
GitHubgithub.com/isharjeelddNew tabLinkedInlinkedin.com/in/muhammad-sharjeel-254a48108New tabUpworkHire me for freelance workNew tab