Skip to content

Bug: Value printed to console is rendered incorrectly in StrictMode #22095

Closed
@Yakimych

Description

@Yakimych

React version: 17.0.2

Steps To Reproduce

The following minimal repro sample is used to indicate a props change in a component:

import React from "react";

export default function App() {
  const [a, setA] = React.useState("a");

  return (
    <>
      <Test a={a} />
      <button onClick={() => setA((oldA) => (oldA === "a" ? "b" : "a"))}>
        Test
      </button>
    </>
  );
}

const Test = ({ a }) => {
  const oldRef = React.useRef(a);

  const hasChanged = oldRef.current !== a;
  if (hasChanged) {
    oldRef.current = a;
  }

  const changedText = hasChanged ? "yes" : "no";
  console.log("Changed: ", changedText);

  return (
    <>
      <div>{a}</div>
      <div>Changed: {changedText}</div>
    </>
  );
};

Clicking the "Test" button prints the value "Changed: yes" to the console, while React renders "no":
yes_no_ref

Note: this works as expected if I remove the <StrictMode> wrapper in index.js.

Link to code example: https://codesandbox.io/s/youthful-jang-2xw3i?file=/src/App.js

The current behavior

"Changed: yes" in printed to console, but "Changed: no" is rendered by React.

The expected behavior

"Changed: yes" in printed to console, "Changed: yes" is rendered by React.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Status: UnconfirmedA potential issue that we haven't yet confirmed as a bug

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions