Skip to content

Bug: shows duplicate the last elements of an array stored with useRef #22564

Closed
@stvkoch

Description

@stvkoch

I'm keeping the last values passed as props without force a re-render, I'm using the useRef to store the elements without re-render the output.

The weird part is that the values showed are different from what I'm storing, duplicating the last elements.

React version: 17.0.2
image

Link to code example:

https://codesandbox.io/s/stupefied-ride-m1did?file=/src/App.js

import React from "react";

const ComR = React.memo(function Compo({ id, value }) {
  const lastElements = React.useRef([0, 0, 0, 0, 0]);
  const [_, ...m] = [...lastElements.current, value]; // remove first and insert last
  lastElements.current = m;
  console.log("rendering", id, value, memo.current);
  return (
    <div>
      {id} - {lastElements.current.join(", ")}
    </div>
  );
});

export default function App() {
  const [value, setValue] = React.useState(0);

  React.useEffect(() => {
    setInterval(() => {
      setValue(Math.ceil(Math.random() * 10000));
    }, 7000);
  }, [setValue]);

  return (
    <div className="App">
      <ComR id="1" value={value} />
    </div>
  );
}

The current behavior

The console.log is showing different what is printing into the component

image

The expected behavior

expects work as linear array operations, since was called/rendered once

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