Description
Backstory
DevTools re-renders function components that use hooks in order to build up metadata to display in the selected element panel. This may cause confusion, since these re-renders will trigger breakpoints and cause unexpected console logging (see this comment). We avoid unnecessary re-renders by caching data (see PR 289) but even so this is likely to be a point of confusion.
Solution
It would be nice if the shallow re-rendering done by DevTools were less observable (e.g. console logs were suppressed to avoid cluttering the console). Breakpoints would still be hit, but that seems like a less common use case.
While we are considering logging, we might also consider if there are additional improvements that could be made, e.g.
- Add a new section to the Components tree that shows the most recently logged messages for a given component.
- Add an option to coalesce render-time logs into a single message that's printed at commit (or error) time to make debug logging easier to read. (Perhaps we could use
console.group
to also indicate the nested structure of these logs.)
The proposals below address both (a) collecting per-component logging info and (b) temporarily disabling console logging while re-rendering for inspection purposes.
API Proposals
1: Modify built-in console
methods
DevTools could spy on the built-in console
methods and disable the pass-through functionality when re-rendering.
Pros
- Requires no effort / code changes for developers to opt in and benefit from this.
- "Just works" for advanced methods like
console.group
andconsole.table
. - "Just works" for third party libraries that may not even be React-specific.
Cons
- Feels questionable to modify native browser APIs.
2: Add React.log
and React.info
API
React will be adding two new logging methods in the upcoming v16.9 release- React.warn
and React.error
(see #15170). These methods decorate console.warn
and console.error
and append the current component stack to any logged messages. We could extend this pattern and add additional log
and info
methods. These APIs could be extended by DevTools as needed.
Pros
- Does not require mutating global APIs.
Cons
- Requires code changes to opt-in.
- Would not cover (or would be a hassle to cover) all
console
methods (e.g.group
) - Would not work for third party components or non-React utility code.
3: Add React.debug(callback)
API
React could add a new debug
API that accepts a callback for general debug operations (most commonly console
logging, but also potentially breakpoints or other things).
Pros
- Works with breakpoints.
- Covers more complex use cases (e.g. pushing to an array for debug purposes).
- Single method rather than mirroring (or spying on) multiple
console
APIs.
Cons
- Requires code changes to opt-in.
- Requires more boilerplate for simple logging use cases.