Skip to content

Bug: React hijacks console functions that may cause unpredictable behavior. #20367

Closed
@infinnie

Description

@infinnie

React version: 17.0.0

Steps To Reproduce

  1. Write the following code below:
    import React from "react";
    import ReactDOM from "react-dom";
    
    let i = 0;
    
    const origLog = console.log.bind(console);
    
    const App = () => {
        const [a, setA] = React.useState(0);
        origLog(i); 
        console.log(i + ': hijacked log');
        origLog("test");
        i++;
        return (
            <button
                onClick={() => {
                    setA(a + 1);
                }}
            >
                click me
            </button>
        );
    };
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(
        <React.StrictMode>
            <App />
        </React.StrictMode>,
        rootElement
    );
  2. While the origLog() function is called in every call to App(), the “hijacked” calls to console.log() would only call the original method every other time, and therefore only even numbers are logged by this function.

Link to code example:

https://codesandbox.io/s/jolly-bush-4ql7z?file=/src/index.js

The current behavior

React automatically “hijacks” the console’s methods to prevent duplicated logs, which might cause unpredictable behaviors.

The expected behavior

The original console methods are called by default even if in the component code.

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions