Console.log is very useful for debugging in React.

console.log in React

console.log() has many use cases, one of them is to check the value of a certain variable throughout lifecycle of the app.

Let’s look at an example where we console.log() a value at different stages of component lifecycle: mount, render, and re-render.

import { useEffect, useState } from "react";
export default function App() {
  useEffect(() => console.log("mount"), []);
  const [count, setCount] = useState(0);
  console.log(count);
  return (
    <div className="App">
      <h1>Hello CodeSandbox</h1>
      <button onClick={() => setCount(count + 1)}>Increase Count</button>
    </div>
  );
}

In this example, we console log the string ‘mount’ when the component mounts. In other words, when it’s initialized.

Clicking the button increases count. Changes to a state variable trigger a re-render.

In the body of the component, we output the state variable count. Every time component re-renders, the method logs the updated value of variable count.

Debug complex code

Maybe you have a complex function or statement that keeps throwing an erorr. One way to simplify it is to insert console.log() at different parts of the code to help you guess which part causes the error.

multiply(args){
    validate(args, 'multiply');
    console.log("something")
    if(Number.isInteger(args)){
      let obj = new Complex(this.r * args, this.i * args);
      return obj;
    }

    console.log("something else")
    else{
      let obj = new Complex((this.r * args.r - this.i * args.i),
            ( this.r * args.i + args.r * this.i));
      return obj;
      }
  }

Looking at the console, the first console.log() runs but the second doesn’t. So the error is in the code that comes after the first console.log() call.

Make sure event handler works

You can also use console.log() to make sure an event handler works as it should.

Add console.log() to the body of event handler. If the event handler works, it should log some message to the console.

const handleChange = (e) => console.log(e.target.value)

...
<input onChange={(e)=>handleChange(e)} />

These are common use cases for using console.log() in React. Still, there may be instances when console.log() does not work as it should.

console.log() shows old state

Sometimes when you use lifecycle methods (or useEffect hook) to update the state, you want to log the state to confirm that it changed.

But the problem is that state always shows previous state, not the current state, as it should.

This is usually due to a simple mistake. Lifecycle methods or useEffect() hooks are often used to load data and store it in the state. If you console.log() within the same callback function, you are going to see the old state, because the state hasn’t updated yet.

To make sure you always get the latest state, move console.log() out of the lifecycle method or useEffect hook. Add it above return statement, before you return JSX.