A magical React Hook that helps you debug components.

Overview

useTilg

Tiny Logger is a magical React Hook to help you debug your components.

You can quickly try out the demo.


Table of Contents


Installation

The package is released as tilg, use:

npm i tilg

to install it with npm. Or you can choose another package manager.


Features

1. Lifecycle Events (What)

Simply insert the useTilg() hook into the component, and it will log the render, mount, unmount events in the console:

import useTilg from 'tilg'

function MyButton() {
  useTilg()
  return <button>Click me</button>
}

lifecycle event logs
Logs of render and mount events.

2. Component Name and Props (Who)

You might noticed that it also displays the name and props of the component, which is very helpful for debugging.

import useTilg from 'tilg'

function MyButton({ text }) {
  useTilg()
  return <button>{text}</button>
}

function Title({ children }) {
  useTilg()
  return <h1>{children}</h1>
}

export default function Page() {
  return (
    <>
      <Title>Welcome!</Title>
      <MyButton text='foo' />
      <MyButton text='bar' />
    </>
  )
}

When there’re multiple elements of the same component being rendered, it adds a counter <MyButton/> (2) for distinguishing so you know who is logging the information:

information logs
Information of the logged components.

3. Debug Message (Why)

Another critical thing is to know why does a component re-renders. useTilg gives you a simple but powerful API for this:

import { useState } from 'react'
import useTilg from 'tilg'

function Counter() {
  const [count, setCount] = useState(0)
  
  useTilg()`count = ${count}`
  
  return <button onClick={() => setCount(count + 1)}>{count}</button>
}

When appending a template literal to the useTilg() call, it will also be displayed as the debug message:

useTilg()`count = ${count}`

debug message
Logs of “count = ?”.

You can know where the message is from, too:

trace
Trace of the message and a link to the code location.

4. What Has Changed? (Why)

Something troubles me a lot when debugging a component is, it’s sometimes hard to know which state has changed and triggered a re-render. useTilg tracks all the arguments in the debug message and tells you which one has changed since the previous render:

import { useState } from 'react'
import useTilg from 'tilg'

function MyApp() {
  const [input, setInput] = useState('')
  const [count, setCount] = useState(0)

  useTilg()`input = ${input}, count = ${count}`

  return (
    <>
      <input onChange={(e) => setInput(e.target.value)} value={input} />
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </>
  )
}

changed argument
A hint for the updated part.

5. Quick Logs (Why)

If you don't need a debug message but only want to quickly log some values, just pass them to the hook directly:

import { useState } from 'react'
import useTilg from 'tilg'

function MyApp() {
  const [input, setInput] = useState('')
  const [count, setCount] = useState(0)

  useTilg(input, count)

  return (
    <>
      <input onChange={(e) => setInput(e.target.value)} value={input} />
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </>
  )
}

value without message
Debug values quickly.


Advanced Features

Markdown

You can use Markdown's code (`), italic (_ or *), and bold (__ or **) syntax in your debug message to make it look nicer:

function MyApp() {
  const [count, setCount] = useState(0)

  useTilg()`**Debug**: \`count\` = _${count}_.`

  return <button onClick={() => setCount(count + 1)}>{count}</button>
}

markdown syntax
Markdown syntax in log messages.

Return Original Value

The useTilg() hook also returns its first argument, or the first value in the template if specified, so you can quickly debug something in-place by wrapping it with useTilg():

  function MyApp() {
    const [count, setCount] = useState(0)

    return <button onClick={() => setCount(count + 1)}>{
+     useTilg(count)
    }</button>
  }

return original value
Log and return the original value.

Auto Deduplication

Even if you have multiple useTilg() hooks in the same component, the lifecycle events will only be logged once per component:

function MyApp() {
  const [input, setInput] = useState('')
  const [count, setCount] = useState(0)

  useTilg()
  useTilg()`input = ${input}`
  useTilg()`count = ${count}`

  return (
    <>
      <input onChange={(e) => setInput(e.target.value)} value={input} />
      <button onClick={() => setCount(count + 1)}>{count}</button>
    </>
  )
}

deduplication
Render, mount, and unmount events will not be duplicated even if you have multiple useTilg() hooks.

CLI Support

If you are running your component during SSR, or running server-side tests, useTilg() properly outputs the result in Node.js CLI too:

function App() {
  const [count, setCount] = useState(42)
  
  useTilg()`The answer is ${{ answer: count }}`

  return <button onClick={() => setCount(count + 1)}>{count}</button>
}

deduplication
Node.js CLI output.


FAQ & Caveats

  • Is it safe to ship code with useTilg to production?
    Although useTilg() does nothing in a production build (process.env.NODE_ENV === 'production') but only an empty function, I encourge you to remove the hook from the source code after finishing the development of your app.

  • How do you implement this hook? What can I learn from the code?
    It is very hacky. Don't do the same thing especially try it in production, or you will be fired.

  • Why not design the API as useTilg`message`?
    Then it will not be identified as a hook, React Refresh and HMR will not work correctly.


License

The MIT License (MIT).

You might also like...
TrackIt - Single Page Application that helps the user track their habits. Implemented with JavaScript/React and an API server which enables the user to sign-in or sign-up in the app.
TrackIt - Single Page Application that helps the user track their habits. Implemented with JavaScript/React and an API server which enables the user to sign-in or sign-up in the app.

TrackIt - Single Page Application that helps the user track their habits. Implemented with JavaScript/React and an API server which enables the user to sign-in or sign-up in the app.

ReviewZon is a ML based tool that helps users make smart decisions by analyzing amazon reviews of a product.
ReviewZon is a ML based tool that helps users make smart decisions by analyzing amazon reviews of a product.

ReviewZon ReviewZon is a ML based tool that helps users make smart decisions by analyzing amazon reviews of a product. Objective Our project’s aim is

A Discord Bot that helps with Action Items
A Discord Bot that helps with Action Items

Installation Install the Actions Bot. Usage /action-react Create an action that

Nlw2 - Proffy - An online study platform that helps people find teachers online
Nlw2 - Proffy - An online study platform that helps people find teachers online

Tecnologias | Projeto | Layout | Licença 🚀 Tecnologias Esse projeto foi desenvo

HackViolet22 - A single platform for women empowerment, that helps them get jobs, get them connected to amazing mentors and exclusive forum for discussion Sentry - a developer-first error tracking and performance monitoring platform that helps developers see what actually matters, solve quicker, and learn continuously about their applications
Sentry - a developer-first error tracking and performance monitoring platform that helps developers see what actually matters, solve quicker, and learn continuously about their applications

Sentry is a developer-first error tracking and performance monitoring platform that helps developers see what actually matters, solve quicker, and learn continuously about their applications.

React Icons Viewer - allows you to search through the react-icons and it allows you to download the icon as png/svg

React Icons Viewer - allows you to search through the react-icons and it allows you to download the icon as png/svg

The bookstore where you can store your best books that you read before. Built with React, Redux, and TailwindCSS.
The bookstore where you can store your best books that you read before. Built with React, Redux, and TailwindCSS.

Bookstore Project In this project, I set up my Bookstore project. It is about making a Bookstore with 2 section BOOKS and CATEGORIES (styles and funct

A meal-based website that gives you all the information you need about your favourite breakfast, lunch and dinner. built with react-typescript & redux.
A meal-based website that gives you all the information you need about your favourite breakfast, lunch and dinner. built with react-typescript & redux.

A meal-based website that gives you all the information you need about your favourite meals. built with react-typescript & redux.

Comments
  • Fix error for react native

    Fix error for react native

    The value of the window.navigator.product property is always Gecko, in any browser. However, in react native window.navigator.product returns ReactNative.

    // react native window object
    {
      "console": { "reportErrorsAsExceptions": true },
      "__jsiExecutorDescription": "HermesRuntime",
      "nativeModuleProxy": {},
      "_WORKLET_RUNTIME": 105553139337248,
      "__reanimatedModuleProxy": {},
      "__BUNDLE_START_TIME__": 127407015.3367917,
      "__DEV__": true,
      "process": { "env": { "NODE_ENV": "development" } },
      "__METRO_GLOBAL_PREFIX__": "",
      "originalConsole": {},
      "ErrorUtils": {},
      "performance": {},
      "regeneratorRuntime": {},
      "originalRegeneratorRuntime": {},
      "navigator": { "product": "ReactNative" },
      "__SYSTRACE": {},
      "__ReactRefresh": {},
      "REACT_NAVIGATION_DEVTOOLS": {},
      "__react_navigation__elements_contexts": {}
    }
    

    So with this field, we can distinguish the browser and fix this issue.

    Before

    image image

    After

    image image
    opened by ergenekonyigit 1
  • Replace spyConsole with vitest builtin spyOn method

    Replace spyConsole with vitest builtin spyOn method

    The story begins when I thought it would be great the I can replace the following function with the deconstructed log function from the console group. https://github.com/shuding/tilg/blob/6acd529c684d20e74c26ad7f5ac9edaba90ee930/src/development.ts#L237-L239

    // can be replaced with
    const { log } = console
    

    It sounds like I failed to change that single line, although it is functional 😅; Cause it makes all tests fail.

    What did I think with myself that I want to change that single line? IMHO: I believe we should test our code in its perfect state and not write testable codes.

    The log function can be mocked by exporting it or replacing its definition in the process.env.NODE_ENV === 'test' environments but they are not slight changes and need moderation and more talk around them.

    Anyway, I'm going to submit my refactor on the console spy functionality with test building usage.

    opened by realamirhe 0
Releases(0.1.1)
  • 0.1.1(Apr 15, 2022)

    Initial release

    What's Changed

    • Fix error for react native by @ergenekonyigit in https://github.com/shuding/tilg/pull/1

    New Contributors

    • @ergenekonyigit made their first contribution in https://github.com/shuding/tilg/pull/1

    Full Changelog: https://github.com/shuding/tilg/commits/0.1.1

    Source code(tar.gz)
    Source code(zip)
Owner
Shu Ding
Be curious. Read widely. Try new things. — aaronsw
Shu Ding
Solana File Sharing System is a Decentralised Application which helps you share files to public Anonymously and no one can trace back to you or change the information since all the files and information is store on decentralised network

Solana File Sharing System is a Decentralized Application that helps users share files anonymously and ensure that the files are available at all times on a decentralized network, not tampered with, verifiable, and secure for all parties involved.

Athar Mohammad 6 Nov 13, 2022
Fruits React App - helps you search fruit online and learn nutrition facts

Fruits Center Fruit Centers helps you search fruit online and learn nutrition facts.

codingwithdidem 5 May 24, 2022
React-play: an open-source web app that helps you learn ReactJS faster with a hands-on practice model

react-play is an open-source web app that helps you learn ReactJS faster with a hands-on practice model. It is a collection of ReactJS projects that you can use to learn ReactJS.

ReactPlayIO 582 Jan 2, 2023
A full-stack web app built with NestJS and ReactJS that helps you find and discover over 500,000+ video games on your device. Powered by RAWG API.

Game Store Monorepo A full-stack web app built with NestJS and ReactJS that helps you find and discover over 500,000+ video games on your device. Powe

Vu Nguyen 120 Dec 29, 2022
Bitloops is Low-Code Workflow Orchestration platform that helps you build backend systems and APIs 10x faster.

Bitloops Bitloops is a scalable open source Firebase substitute that can support any database and workflow orchestration. We’re building Bitloops usin

Bitloops 21 Aug 9, 2022
A set of packages that helps you integrate the Glow Solana Wallet into your dApp

Glow JS This is a set of packages that helps you integrate the Glow Solana Wallet into your dApp. ?? Video Overview Packages Here is a set of packages

Glow 25 Dec 5, 2022
A windows desktop application that helps you manage your notes and txt files.

txt note manager A windows desktop application that helps you manage your notes and txt files. Shows all txt files in a folder of your choice. Make ne

Kevin Hoang 1 May 7, 2022
An application that helps you choose a place to travel

worldtrip ✈️ An application that helps you choose a place to travel! View Demo » ?? In production ?? Table of Contents About The Project Features Buil

Daniel Souza 1 May 2, 2022
React Todo List - This project helps to consolidate my knowledge about React, components, props, state, and hooks

React Todo List This project helps to consolidate my knowledge about React, components, props, state, and hooks, by following a tutorial. Screenshot B

null 7 Dec 15, 2022
ExpenseApp is an app to see you expense history, income history and help you notes what you're buying lately

ExpenseApp is an app to see you expense history, income history and help you notes what you're buying lately

Rizki Maulana Citra 27 Dec 27, 2022