Repo of the Day
shuding/tilg
Published: Apr 27, 2024
Open repository ↗A magical React Hook that helps you debug components.
Summary
useTilg is a React Hook that logs render, mount, and unmount events to the console, along with the component's name and props. It supports custom debug messages via tagged template literals and highlights which values changed since the previous render, so engineers can quickly see why a component re-rendered.
What it is useful for
useTilg is useful when you need quick visibility into React component behavior without scattering console.log calls. Common situations include:
- Tracing which component is re-rendering too often during development.
- Seeing the human-readable name and current props of the component being logged. When multiple instances of the same component render, it appends a counter (e.g.
<MyButton/> (2)) to distinguish them. - Pinpointing which prop or state value triggered a re-render, by inspecting which interpolated argument changed between renders.
- Logging values inline by wrapping them with
useTilg(value), since the hook returns its first argument unchanged. - Debugging in environments where the browser DevTools are not available. The README documents CLI output that works in Node.js, including for SSR and server-side tests.
- Formatting debug messages using Markdown syntax (code, italic, bold) for readability in the logs.
How engineers can use it
The README documents installation with npm i tilg. After installing, import the hook and call it inside a function component:
import useTilg from 'tilg'
function MyButton({ text }) {
useTilg()
return <button>{text}</button>
}
To see why a component re-rendered, append a tagged template that interpolates the values you care about:
function MyApp() {
const [input, setInput] = useState('')
const [count, setCount] = useState(0)
useTilg()`input = ${input}, count = ${count}`
// ...
}
If you only need a quick snapshot of values without a message, pass them as arguments: useTilg(input, count).
The README also notes a couple of documented caveats. In a production build (process.env.NODE_ENV === 'production'), useTilg becomes an empty function, and recommends deleting it from source before shipping. It also explains that calling useTilg\message`directly as a tagged template would not be recognized as a hook, breaking React Refresh and HMR, which is why the documented API isuseTilg()`message``. Calling the hook multiple times in the same component deduplicates lifecycle events automatically.