Ben Edelstein Founder @LogRocket, formerly @Google

Leveraging the Console API in React apps

2 min read 740

Most JavaScript developers are familiar with the console API, particularlyconsole.log(). However, there are a number of lesser-known console methods that are quite useful in both development and debugging workflows. In this post, I’ll demonstrate some of the these methods and show how they can be particularly helpful when building React apps.

Console.time()

The time method lets you measure the time between different events:

For each timer, you can specify a name (“Timer 1” in this case) which lets you see the result in the console. console.time and console.timeEnd for a given timer don’t have to be in the same closure- they are global across your app. This is helpful if you want to time a transaction that takes place across different React components, or Redux actions. For example, by placing a timer around a Redux action dispatch, you can see how long the effects of the action take to propagate through your UI.

At the component level, console.time lets you see approximately how long a given component takes to mount and render:

Here, we start the timer in the component’s constructor and end it in componentDidMount, which times the first mount + render cycle.

Console.count()

console.count() is an appropriately named method that counts a given value. This doesn’t warrant too much explanation, but I’ll note that it is helpful for counting how many times a component’s render method is called. This is great when debugging performance issues, and removes the need to manually count how many times a console.log() is printed in the component’s render method.

Console.group()

console.group() lets you group together logs under an expandable tab in the console. This is helpful for keeping related logs together without letting the console become too noisy.

After adding aconsole.group() statement, all subsequent log statements are placed under the group heading. To stop placing logs in the group, simply add console.groupEnd().

The output above corresponds with starting a console group in a React component’s constructor: console.group('ListView Component'). Each subsequent log is simply a console.log() statement in the respective lifecycle methods. Grouping together logs in an individual component helps keep the console clean, and makes it easier to find the logs associated with a component of interest.

Using the console API with LogRocket

In the past, the console API was mainly used during development, but with the rise in popularity of production frontend logging tools like LogRocket, which capture all console output, it has become an increasingly common practice to strategically place log statements in frontend code. This is helpful in a number of cases.

When trying to understand a bug report, it is often helpful to know the value of a given variable right before the bug occurred. Adding a log statement around that variable (eg. console.log('EVENT_COUNT', eventCount)) means that the next time the bug occurs, the value of the variable is captured in the logs.

While error reporting tools (eg. Sentry, BugSnag, etc) are great for capturing exceptions, there are often “softer” errors that don’t warrant full-on alerting. An example might be an unexpected state of the application, or an edge case that shouldn’t happen, but isn’t an explicit error. For these situations, it can be helpful to use console.warn and console.error to express the condition. Then, when investigating a bug report, you can look through the session logs to see if any such warnings or errors occurred. LogRocket also lets you search logs across all sessions, so you can answer questions like “how many times does this edge case actually happen”!

Bonus: fun with console styles

If you’ve ever opened the console on facebook.com, you’ve seen their warning against pasting shady JavaScript into the console.

To achieve this effect, they use the %c operator which, when added to a logged string, applies CSS from the next argument.



Aside from this type of warning, I’m not aware of too many use cases for this API, but if you have figured out a creative way of using it, please say so in the comments 🙂

Further Reading

 

Get setup with LogRocket's modern React error tracking in minutes:

  1. Visit https://logrocket.com/signup/ to get an app ID.
  2. Install LogRocket via NPM or script tag. LogRocket.init() must be called client-side, not server-side.
  3. $ npm i --save logrocket 

    // Code:

    import LogRocket from 'logrocket';
    LogRocket.init('app/id');
    Add to your HTML:

    <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script>
    <script>window.LogRocket && window.LogRocket.init('app/id');</script>
  4. (Optional) Install plugins for deeper integrations with your stack:
    • Redux middleware
    • ngrx middleware
    • Vuex plugin
Get started now
Ben Edelstein Founder @LogRocket, formerly @Google

Leave a Reply